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

I have an array with tags that is part of a document, for example [red, green, blue, white, black)

Now I want to find all documents that have red and blue.

+4
source share
2 answers

Use the $ all clause to search for records that match both red and blue conditions.

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

If you want entries matching red or blue, you can use the $ in clause.

 db.my_collection.find({tags: { $in : ["red","blue"]}}) 
+11
source

Also, if someone asks how to cancel the elemental search, that is, find a record that matches both β€œred” and β€œblue”, and does NOT match β€œgreen” and β€œwhite”, this can be achieved with using $ nin , which may be unclear when someone reads $ nin docs ( http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24nin - the description of the parsing was difficult for me):

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

This is very cool because it allows a relatively good negation search syntax:

 tokenRequired1 tokenRequired2 !tokenForbidden1 !tokenForbidden2 

A very natural Gmail style search.

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

+3
source

All Articles