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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With