Querying array elements with Mongo

…衆ロ難τιáo~ 提交于 2019-12-18 01:33:56

问题


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

    )

回答1:


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.




回答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] }




回答3:


Why do people write scalable applications for smoothies?

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



来源:https://stackoverflow.com/questions/3308119/querying-array-elements-with-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!