0

考虑以下文档:

{
    "_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
]}
4

1 回答 1

3

我相信你在这里寻找$elemMatch,从而确保对应的AttributeNameAttributeValue在多值字段的相同元素中(http://docs.mongodb.org/manual/reference/operator/elemMatch/):

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

尝试类似的东西

于 2013-03-04T13:28:53.853 回答