147

I am using mongodb now.

I have a blogpost collection, and it has a tags field which is an array, e.g.

blogpost1.tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5']
blogpost2.tags = ['tag2', 'tag3']
blogpost3.tags = ['tag2', 'tag3', 'tag4', 'tag5']
blogpost4.tags = ['tag1', 'tag4', 'tag5']

How can I do these search

  1. contains tag1
  2. contains ['tag1','tag2']
  3. contains any of ['tag3', 'tag4']

2 Answers 2

224

Try this out:

db.blogpost.find({ 'tags' : 'tag1'}); //1
db.blogpost.find({ 'tags' : { $all : [ 'tag1', 'tag2' ] }}); //2
db.blogpost.find({ 'tags' : { $in : [ 'tag3', 'tag4' ] }}); //3
Sign up to request clarification or add additional context in comments.

7 Comments

This is well documented in the help: mongodb.org/display/DOCS/…
for the $all does it mean all elements AND in the expressed order or is it just unordered ?
@ScottHernandez I do not see that they mention that the field you are using as your search can be an array, and how that is handled. "field : { $in : array }". What happens when you search for an array within an array of arrays? Not specified.
Is there any INDEXING we can do on array's to stop duplicate? If yes, please guide how.
@redben its unordered like written in the docs: $all operator DOCS. Just read the example part and you will see.
|
5

My experience is that for (2) the following solution is much faster than the one with "$all":

db.blogpost.find({ $and: [ {tags: 'tag1'} ,{tags: 'tag2'} ] });

but to be honest, I do not not why. I would be interested in, if anyone knows.

5 Comments

By the way, just tested it on indexed keywords list. Absolutely the same result with $and and $all
Maybe that changed with newer versions in the meantime.
It's circumstantial. For the "$and", mongodb making a logical "and" operation. Therefore if the first expression is false, the second are not taken into consideration. This means less processing.
But that should happen with '$all' also, shouldn't it!?
$all is probably two lookups on an index, $and is probably one lookup with a sequential scan on the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.