使用Mongo查询数组元素

27

如何查询含有苹果的冰沙?(下面是包含3个文档的集合)

_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

    )
3个回答

47
如果您只是运行以下查询,MongoDB 足够聪明,可以理解您的意图。
{ ingredients: "apple" }

Mongo会检查ingredients是一个列表,并且只返回包含"apple"的文档。


-2
文档中得知:
注意:包含数组的字段与条件运算符匹配时,只有一个项匹配
因此,以下查询: db.collection.find( { field: { $gt:0, $lt:2 } } ); 将匹配包含以下字段的文档: { field: [-1,3] }

-6

为什么人们要编写可扩展的应用程序来制作果汁?

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


5
这是一个无效的查询。$in值必须是一个数组。例如:{"ingredient": {$in: ["apple","cinnamon","sugar"]}}将测试ingredient字段是否包含3个列出的值中的一个。 - Aneil Mallavarapu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接