Andrew Serff
Andrew Serff

Reputation: 2127

Return only array value in mongo projection

Is there a way to return only the value of a property in a mongodb projection? For instance, I have a document that has a property whose value is an array. I want the return object from a query to be the array only, not property: [ .. ]. Example:

Document:

db.test.insert({ name: "Andrew",
   attributes: [ { title: "Happy"},
                 { title: "Sad" }
               ]
});

Query:

db.test.find({name: "Andrew"},{attributes:1, "_id":0});

That returns:

{ "attributes" : [ { "title" : "Happy" }, { "title" : "Sad" } ] }

I want it to return on the array:

[ { title: "Happy"},
  { title: "Sad" }
]

Is there a way to do that? Thanks

Upvotes: 8

Views: 12085

Answers (1)

Derick
Derick

Reputation: 36794

JSON doesn't allow the toplevel to be an array so a normal query doesn't allow this. You can however do this with the aggregation framework:

> db.test.remove();
> db.test.insert({ name: "Andrew", attributes: [ { title: "Happy"}, { title: "Sad" } ] });
> foo = db.test.aggregate( { $match: { name: "Andrew" } }, { $unwind: "$attributes" }, { $project: { _id: 0, title: "$attributes.title" } } );
{
    "result" : [
        {
            "title" : "Happy"
        },
        {
            "title" : "Sad"
        }
    ],
    "ok" : 1
}
> foo.result
[ { "title" : "Happy" }, { "title" : "Sad" } ]

This however, does not create a cursor object that find does.

Upvotes: 7

Related Questions