How do you do an AND query on an array in mongodb?

2.4k views Asked by At

I have an array with tags which is part of a document, eg ["red", "green", "blue", "white", "black"]

Now I want to find all documents, which have red AND blue.

2

There are 2 answers

0
Hates_ On BEST ANSWER

Use the $all condition to find records that match both "red" and "blue" conditions.

db.my_collection.find({tags: { $all : ["red","blue"]}})

If you want records that match either "red" or "blue" then you can use the $in condition.

db.my_collection.find({tags: { $in : ["red","blue"]}})
0
Jakub P. On

Also in case someone is wondering how to negate itemized search, i.e. find record that match both "red" and "blue" and DO NOT match "green" and "white" this can be accomplished with the $nin operator, which may not be obvious when someone is reading $nin docs (http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24nin - parsing description was tricky for me):

db.my_collection.find({tags: { $all : ["red","blue"], $nin : ["green", "white" ]}})

This is very cool, as it allows relatively nice search syntax with negation:

tokenRequired1 tokenRequired2 !tokenForbidden1 !tokenForbidden2

Very natural, Gmail-style search.

As suggested here and here you could do full text search if you create an array of all tokens from a record, though I have no idea if it's efficient or even the best way to do it.