crystaldust
crystaldust

Reputation: 73

MongoDB aggregation: How to extract the field in the results

all!

I'm new to MongoDB aggregation, after aggregating, I finally get the result:

"result" : [
    {
        "_id" : "531d84734031c76f06b853f0"
    },
    {
        "_id" : "5316739f4031c76f06b85399"
    },
    {
        "_id" : "53171a7f4031c76f06b853e5"
    },
    {
        "_id" : "531687024031c76f06b853db"
    },
    {
        "_id" : "5321135cf5fcb31a051e911a"
    },
    {
        "_id" : "5315b2564031c76f06b8538f"
    }
],
"ok" : 1

The data is just what I'm looking for, but I just want to make it one step further, I hope my data will be displayed like this:

"result" : [
     "531d84734031c76f06b853f0",
     "5316739f4031c76f06b85399",
     "53171a7f4031c76f06b853e5",
     "531687024031c76f06b853db",
     "5321135cf5fcb31a051e911a",
     "5315b2564031c76f06b8538f"
],
"ok" : 1

Yes, I just want to get all the unique id in a plain string array, is there anything I could do? Any help would be appreciated!

Upvotes: 1

Views: 1937

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151072

All MongoDB queries produce "key/value" pairs in the result document. All MongoDB content is basically a BSON document in this form, which is just "translated" back to native code form by the driver to the language it is implemented in.

So the aggregation framework alone is never going to produce a bare array of just the values as you want. But you can always just transform the array of results, as after all it is only an array

var result = db.collection.aggregate(pipeline);

var response = result.result.map(function(x) { return x._id } );

Also note that the default behavior in the shell and a preferred option is that the aggregation result is actually returned as a cursor from MongoDB 2.6 and onwards. Since this is in list form rather than as a distinct document you would process differently:

var response = db.collection.aggregate(pipeline).map(function(x) {
    return x._id;
})

Upvotes: 4

Related Questions