在MongoDB中,从文档中获取单个字段数组的最简单方法是什么

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

本文关键字:数组 最简单 方法 是什么 字段 获取 MongoDB 文档 单个      更新时间:2023-09-26

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

{
  _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文档大小限制的信息