2013-03-04 163 views
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 
]} 

回答

3

我相信你正在尋找$elemMatch這裏,由此可以確保把對應的AttributeNameAttributeValue是一個多值字段(http://docs.mongodb.org/manual/reference/operator/elemMatch/)相同的元素:

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

嘗試類似這樣的東西