[英]in mongodb, whats the easiest way to get an array of a single field from the documents
假设我在我的收藏中有这些文件:
{
_id: xxx,
region: "sw"
},
{
_id: yyy,
region: "nw"
}
我想最终得到这样的数组:
['sw', 'nw']
我已经尝试了mongodb聚合/组和mapreduce,但我总是最终得到一个文档数组,然后必须再次循环才能获得单个数组。 有没有办法在单个mongodb查询中实现这一点,还是总是需要查询然后进一步处理?
尝试这个:
db.foo.aggregate(
{$group: {_id: null, region: {$push: "$region"}}}
).result[0].region
或者如果你想使用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
或使用组(感谢@Travis添加此组):
db.foo.group({
reduce: function (curr, result) {
result.regions.push(curr.region);
},
initial: { regions: [] }
})[0].regions
注意
使用这些方法,您必须记住BSON文档大小限制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.