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 )
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With