在单个嵌套文档中对多个字段和值进行MongoDB $and查询

6
我正在寻找一种查询这样一个集合的方法:
```html

我正在寻找一种查询这样一个集合的方法:

```
[{ 
  name: "Parent 1",
  items: [
    { name: "Child 1", age: "60" },
    { name: "Child at heart", age: "27" }
  ]
 },

 {
  name: "Parent 2",
  items: [
    { name: "Child 3", age: "10" },
    { name: "Child 4", age: "15" },
    { name: "Child at heart", age: "60" }
  ]
 }
]

使用以下查询语句:
db.collection.find( 'items.name' => "Child at heart", 'items.age' => "60" )

我想要查询只包含名称为“Parent 2”的对象结果。也就是说,我想要查询文档,查找包含嵌入项的文档,该嵌入项在同一嵌入文档中具有“Child at heart”和“60”年龄的名称。但是这个查询返回了“Parent 1”和“Parent 2”两个文档。
如何使用$and条件查询同一嵌入文档中的不同字段?
谢谢。

1
使用 $elemMatch:http://docs.mongodb.org/manual/reference/operator/elemMatch/ - Abhishek Kumar
1个回答

9
这里的问题在于$and将每个条件应用于所有嵌入文档,并且只要任何嵌入文档匹配,就将该文档视为符合条件。它不关联这些条件。
您需要的运算符是$elemMatch。它执行您所寻找的相关性。下面是正确的查询:
db.collection.find({items: {$elemMatch: {name: 'Child at heart', age: '60'} }})

items是您要搜索的数组名称。

在您的示例数据上查询的输出:

{
"_id" : ObjectId("51a012f0ac3dfe4f0c05ca89"),
"name" : "Parent 2",
"items" : [
    {
        "name" : "Child 3",
        "age" : "10"
    },
    {
        "name" : "Child 4",
        "age" : "15"
    },
    {
        "name" : "Child at heart",
        "age" : "60"
    }
]
}

感谢您详细的回复,Paul。我已经接受这个答案了。 - Bramanga

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