27

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

    )
ljs.dev
  • 4,449
  • 3
  • 47
  • 80
Devrim
  • 2,826
  • 5
  • 25
  • 31

3 Answers3

47

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.

Steven Surowiec
  • 10,030
  • 5
  • 32
  • 37
-2

From the documentation:

Note: Fields containing arrays match conditional operators, if only one item matches.

Therefore, the following query:

db.collection.find( { field: { $gt:0, $lt:2 } } );

Will match a document that contains the following field:

{ field: [-1,3] }

codeape
  • 97,830
  • 24
  • 159
  • 188
-6

Why do people write scalable applications for smoothies?

db.find({"ingredients":{$in: "apple"}});

Nayan Jain
  • 188
  • 9
  • 5
    That is an invalid query. The $in value must be an array. For example: ```{"ingredient": {$in: ["apple","cinnamon","sugar"]}}``` Would test whether the ingredient field contains one of the 3 listed values. – Aneil Mallavarapu Apr 17 '12 at 05:41