0

假设我的收藏中有这些文件:

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

我想最终得到一个这样的数组:

['sw', 'nw']

我已经尝试过 mongodb 聚合/组和 mapreduce,但我总是得到一个文档数组,然后必须再次循环才能得到一个数组。有没有办法在单个 mongodb 查询中实现这一点,还是总是需要查询然后进一步处理?

4

1 回答 1

2

试试这个:

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 文档大小限制

于 2013-11-08T19:08:04.210 回答