Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only array value in mongo projection

Tags:

mongodb

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

like image 663
Andrew Serff Avatar asked Feb 05 '13 16:02

Andrew Serff


1 Answers

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.

like image 59
Derick Avatar answered Oct 30 '22 21:10

Derick