Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying array elements with Mongo

How can I query the smoothies that have apple in them? (below is a collection with 3 documents)

_id => 1 name => 'best smoothie'  ingredients => Array     (         [0] => apple         [1] => raspberry         [2] => orange         [3] => banana     ) _id => 2 name => 'summer smoothie'  ingredients => Array     (         [0] => lemon         [1] => mint      ) _id => 3 name => 'yogurt smoothie'  ingredients => Array     (         [0] => apple         [1] => blueberry      ) 
like image 893
Devrim Avatar asked Jul 22 '10 11:07

Devrim


People also ask

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I pull all elements in an array in MongoDB?

The $pullAll operator removes all instances of the specified values from an existing array. Unlike the $pull operator that removes elements by specifying a query, $pullAll removes elements that match the listed values.

How do I match an array element in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

How do I query multiple values in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.


1 Answers

If you simply run the below query MongoDB is smart enough to figure out what you're trying to do.

{ ingredients: "apple" } 

Mongo will see that ingredients is a list and only return documents that contain "apple" some where in that list.

like image 103
Steven Surowiec Avatar answered Sep 24 '22 21:09

Steven Surowiec