Returns only array value in mongo projection

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

Document

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

Query:

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

This returns:

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

I want it to return to an array:

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

Is there any way to do this? Thanks

+5
source share
1 answer

JSON does not allow the toplevel array to be an array, so a regular request does not allow this. However, you can do this using the aggregation structure:

> 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 the cursor object that it finds.

+3
source

All Articles