0

我想查找元素 0 为 的所有ingredients文档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

        )
}

借用的示例 -使用 Mongo 查询数组元素

4

3 回答 3

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"
        ]
}
于 2013-06-21T12:14:17.010 回答
1

您应该使用$unwindmongo$project函数。

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

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

于 2013-06-21T07:32:29.107 回答
0

我看不到任何方法可以使用 simple 来实现这一点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" } ] }
于 2013-06-21T07:32:02.110 回答