[英]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. 我已经尝试了mongodb聚合/组和mapreduce,但我总是最终得到一个文档数组,然后必须再次循环才能获得单个数组。 Is there a way to achieve this in a single mongodb query or will it always require a query and then further processing? 有没有办法在单个mongodb查询中实现这一点,还是总是需要查询然后进一步处理?
Try this: 尝试这个:
db.foo.aggregate(
{$group: {_id: null, region: {$push: "$region"}}}
).result[0].region
Or if you want to use map-reduce: 或者如果你想使用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): 或使用组(感谢@Travis添加此组):
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 使用这些方法,您必须记住BSON文档大小限制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.