More Than Five
More Than Five

Reputation: 10429

Return only specify object property from array of values

My collection is like such in 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"}
    ]
}, 
...

i.e. Each object has an array of options, where each option is an object literal.

I want to find the colour for the option where the age is "15".

I do:

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

But this give me the entire object - some noise To narrow the scope of what is returned I do:

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

But this give me...

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

Is there any way I could just get...

{"color": "blue"} 

returned

Upvotes: 1

Views: 852

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151220

Wrong position of the $ operator:

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

If you just want the color for the specified age then you need to use the aggregation framework:

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

Upvotes: 1

Related Questions