How to find all documents containing a certain value with MongoDB

Problem

I'm using nodejs and mongodb. x is a variable containing a string (certain color). now, I would like to create a query (in nodejs) that retrieves all docs which their colors field (which is a list of strings, in this case a list of colors) contains the string x. How should I write it in nodejs?

Problem courtesy of: Liatz

Solution

Your question is a bit confusing, because in the first paragraph you are asking for an OR relation, but your example describes an AND relation.

When you want to find all documents which have red OR green, you have to use the $in operator:

db.collection.find({ colors: { $in:[ "red", "green" ]} });

When you want to find all documents which have red AND green (and maybe also others), you have to use $all:

db.collection.find({ colors: { $all:[ "red", "green" ]} });

Source: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries

Solution courtesy of: Philipp

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.