2014-06-12 49 views
0

我的收藏在Mongo中就像這樣。返回僅從值數組中指定對象屬性

{ 
    "_id": 123, 
    version: 2, 
    property: "toenail", 
    options: [ 
     {"color": "blue", age: "15"}, 
     {"color": "black", age: "27"} 
    ] 
}, 
{ 
    "_id": 124, 
    version: 12, 
    property: "tooth", 
    options: [ 
     {"color": "green", age: "5"}, 
     {"color": "yellow", age: "7"} 
    ] 
}, 
... 

即每個對象都有一個選項數組,其中每個選項都是對象文字。

我想找到年齡爲「15」的選項的顏色。

我做的:

db.saksMongoItem.find({"options.age":"15" }) 

但是,這給我的整個對象 - 一些噪音 要縮小返回我做什麼範圍:

db.saksMongoItem.find({"options.age":"15" }, {"options.color.$":1}) 

但是,這給我...

{ "_id" : NumberLong(123), "options" : [ { "color" : "blue", "age:15")]} 

有什麼辦法,我可以只得到...

{"color": "blue"} 

返回

+0

有沒有從沒有解決你的問題的答案中缺少的東西estion? –

回答

1

$操作的錯誤的位置:

db.saksMongoItem.find({"options.age":"15" }, {"options.$":1}) 

如果你只是想爲特定年齡的顏色,那麼你需要使用聚合框架:

db.saksMongoItem.aggregate([ 
    { "$match": { "options.age":"15" } }, 
    { "$unwind": "$options" }, 
    { "$match": { "options.age":"15" } }, 
    { "$project": { 
     "_id": 0, 
     "color": "$options.color" 
    }} 
])