如何使用MongoDB在数组中的特定位置查找包含元素的文档?

时间:2013-06-21 06:38:03

标签: mongodb

我想找到ingredients的元素0为apple的所有文档。所以我想得到1号文件和3号文件,但不是2.是否可以在Mongo本地使用这种东西?

这个例子没有意义,但是我的应用程序太复杂了,不能放在这里。

{
    _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
            [2] => apple

        )
}

{
    _id => 3
    name => 'yogurt smoothie' 
    ingredients => Array
        (
            [0] => apple
            [1] => blueberry

        )
}

示例借用 - Querying array elements with Mongo

3 个答案:

答案 0 :(得分:4)

您可以使用数组位置运算符(docs)。有用的是,您可以使用相同的模式并指定特定的索引,而不是使用通用的$语法。

假设这是您的数据:

> db.so1.insert({name:"best smoothie", ingredients: ['apple','raspberry','orange','banana']})
> db.so1.insert({name:"summer smoothie", ingredients: ['lemon','mint','apple']})
> db.so1.insert({name:"yogurt smoothie", ingredients: ['apple','blueberry']})

如果要将搜索限制为仅索引位置0,只需将其添加到数组属性名称,如下所示:

> db.so1.find({'ingredients.0':'apple'})

结果:

{
        "_id" : ObjectId("51c4425ff227e278e59f5df5"),
        "name" : "best smoothie",
        "ingredients" : [
                "apple",
                "raspberry",
                "orange",
                "banana"
        ]
}
{
        "_id" : ObjectId("51c4428af227e278e59f5df7"),
        "name" : "yogurt smoothie",
        "ingredients" : [
                "apple",
                "blueberry"
        ]
}

答案 1 :(得分:1)

您应该将$unwind$project mongo函数一起使用。

`$unwind` - split up array
`$project` - add smth like index for each splitted element

之后可以使用简单的findOne语句。

答案 2 :(得分:0)

我看不到使用简单array实现此目的的任何方法。但是,您可以使用一系列哈希来执行此操作:

> db.collections.find()
{ "_id" : ObjectId("51c400d2b9f10d2c26817c5f"), "ingredients" : [ { "value1" : "apple" }, { "value2" : "orange" } ] }
{ "_id" : ObjectId("51c400dbb9f10d2c26817c60"), "ingredients" : [ { "value1" : "mint" }, { "value2" : "apple" } ] }
{ "_id" : ObjectId("51c400e1b9f10d2c26817c61"), "ingredients" : [ { "value1" : "apple" }, { "value2" : "lemon" } ] }

> db.collections.find({ ingredients: { $elemMatch: { value1: 'apple' }}})
{ "_id" : ObjectId("51c400d2b9f10d2c26817c5f"), "ingredients" : [ { "value1" : "apple" }, { "value2" : "orange" } ] }
{ "_id" : ObjectId("51c400e1b9f10d2c26817c61"), "ingredients" : [ { "value1" : "apple" }, { "value2" : "lemon" } ] }
相关问题