2014-06-12 48 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" 
    }} 
])