简体   繁体   中英

in mongodb, whats the easiest way to get an array of a single field from the documents

Assume, I have these documents in my collection:

{
  _id: xxx,
  region: "sw"
},
{
  _id: yyy,
  region: "nw"
}

I want to end up with an array like this:

['sw', 'nw']

I have tried mongodb aggregation/group and mapreduce but I always end up with an array of documents that then have to be looped through again to get to a single array. Is there a way to achieve this in a single mongodb query or will it always require a query and then further processing?

Try this:

db.foo.aggregate(
    {$group: {_id: null, region: {$push: "$region"}}}
).result[0].region

Or if you want to use map-reduce:

db.foo.mapReduce(
    function() { emit(null, this.region)},
    function(key, values) {
        result = {region: []};
        values.forEach(function(x){ result.region.push(x); });
        return result;
    },
    {out: {inline: 1}}
).results[0].value.region

Or using group (thanks to @Travis for adding this one):

db.foo.group({
  reduce: function (curr, result) {
    result.regions.push(curr.region);
  },
  initial: { regions: [] }
})[0].regions

Note

Using each of this methods you have to remember about BSON Document Size Limits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM