Reputation: 2434
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?
Upvotes: 0
Views: 49
Reputation: 330063
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
Upvotes: 2