Querying array elements with Mongo

Devrim picture Devrim · Jul 22, 2010 · Viewed 16.5k times · Source

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

    )

Answer

Steven Surowiec picture Steven Surowiec · Jul 22, 2010

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.