【问题标题】:in mongodb, whats the easiest way to get an array of a single field from the documents在 mongodb 中,从文档中获取单个字段数组的最简单方法是什么
【发布时间】:2013-11-08 19:00:26
【问题描述】:

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

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

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

['sw', 'nw']

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

【问题讨论】:

    标签: javascript mongodb mapreduce aggregation-framework


    【解决方案1】:

    试试这个:

    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 Document Size Limits

    【讨论】:

    • 我继续并添加了另一个我能想到的选项,而不是我自己的答案。
    • 谢谢,那肯定更近了。但我最终得到: { "0" : "NW", "1" : "SW" } 我仍然需要处理才能获得一个简单的数组。
    • @Travis 很棒。我正打算自己做:)
    • @kidbrax 你能解释一下吗?对于示例中的文档,这些都不应该给你{ "0" : "NW", "1" : "SW"}。你用的是什么版本的 MongoDB?
    • 是的,没关系。我的数据库客户端(Robomongo)出于某种原因以这种方式输出它。当直接在 mongo shell 中完成时,它工作得很好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 2015-02-13
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    相关资源
    最近更新 更多