MongoDB中嵌套的$and或分组的$and

MongoDB中嵌套的$and或分组的$and,mongodb,Mongodb,考虑以下文件: { "_id" : ObjectId("5130f9a677e23b11503fee55"), "ItemType" : "Bicycle" "Attributes" : [{ "AttributeName" : "Spare Tire", "AttributeValue" : "1" }, { "AttributeName" : "With helmet?", "Attr

考虑以下文件:

{
    "_id" : ObjectId("5130f9a677e23b11503fee55"),
    "ItemType" : "Bicycle"
     "Attributes" : [{
         "AttributeName" : "Spare Tire",
         "AttributeValue" : "1"
     }, {
         "AttributeName" : "With helmet?",
         "AttributeValue" : "0"
     }, {
         "AttributeName" : "Number of Locks",
         "AttributeValue" : "1"
     }]
}
如何编写查询以获取带备用轮胎和无头盔的自行车

我尝试了以下方法,但它不能满足我的需求

{ 
"$and" : 
[ 
    { "ItemType" : "Bicycle" }, 
    { "$and": 
        [{ "Attributes.AttributeName" : "With helmet?" }, 
         { "Attributes.AttributeValue" : "0" }
   ]},
    { "$and": 
        [{ "Attributes.AttributeName" : "Spare Tire" }, 
         { "Attributes.AttributeValue" : "1" }
   ]}
]}
似乎只要有一个值与
Attributes.AttributeValue
匹配,不管附带的
Attributes.AttributeName
,它就会返回该文档。这就像有这样一个查询:

{ 
"$and" : 
[ 
    { "ItemType" : "Bicycle" },                        //true
    { "Attributes.AttributeName" : "With helmet?" },   //true 
    { "Attributes.AttributeName" : "Spare Tire" },     //true
    { "Attributes.AttributeValue" : "0" },             //any
    { "Attributes.AttributeValue" : "1" }              //any
]}

我相信您正在这里寻找
$elemMatch
,它可以确保相应的
AttributeName
AttributeValue
位于多值字段()的同一元素中:


尝试类似的方法

我相信您在这里寻找的是
$elemMatch
,它可以确保相应的
AttributeName
AttributeValue
位于多值字段()的同一元素中:

试试那样的

{
    ItemType: 'Bicycle', 
    $and:[
        {"Attributes": {$elemMatch:{AttributeName: 'With helmet?', AttributeValue: 0 }}},
        { //Next match }
    ]
}