【问题标题】:mapReduce or aggregation for averages of nested properties嵌套属性平均值的 mapReduce 或聚合
【发布时间】:2014-04-30 21:03:42
【问题描述】:

我的收藏有这样的文档:

一天

--小时

----分钟

...其中每一小时是一天的一个属性,每一分钟是一个小时的一个属性:

///first hour, first minute ... last hour, last minute
{
 0: {0:{x:1, y:2}...59:{x:3, y:8}}
 ...
 23: {0:{x:1, y:2}...59:{x:3, y:8}} 
}

我想平均分钟属性的值以返回如下文档集合:

//first hour, average values ... last hour, average values

{
0:{x:2, y:5}
...
23:{x:2, y:5}
}

我可以使用 mapReduce 或聚合管道来执行此操作吗?如何?

一个小问题:我还想过滤掉这样的预格式化分钟:

59: {x:0, y:0} // zero means null record 

【问题讨论】:

  • 我意识到这是转换单个文档而不是聚合或减少文档(更多的映射而不是减少),但我想知道我是否可以为此使用 mongodb 而不是去较慢的业务层( node.js)。

标签: mongodb mapreduce aggregation-framework


【解决方案1】:

是的,这是没有 reducer 的直接 mapReduce 逻辑。

所以考虑到你的结构有点像这样:

{
    "series": {
        0:  { 0:{x:1, y:2}, 1: { x:0, y:0 }, 59:{x:3, y:8} },
        23: { 0:{x:1, y:2}, 59:{x:3, y:8} } 
    }
}

然后你定义一个映射器:

var mapper = function () {

  var output = {};

  for ( h in this.series ) {

    var minutes = {x: 0, y: 0};
    var count = 0;

    for ( m in this.series[h] ) {
      if ( ( this.series[h][m].x != 0 ) &&
           ( this.series[h][m].y != 0 ) )
      {
        minutes.x += this.series[h][m].x;
        minutes.y += this.series[h][m].y;
        count++;
      }
    }

    minutes.x = Math.floor( minutes.x / count );
    minutes.y = Math.floor( minutes.y / count );

    output[h] = minutes;

  }

  emit( this._id, output );

};

然后运行 ​​mapReduce:

db.series.mapReduce(mapper,function(){},{ out: { inline: 1 } })

这会给你输出:

    "results" : [
            {
                    "_id" : ObjectId("53618345e10ce3c73df3ff24"),
                    "value" : {
                            "0" : {
                                    "x" : 2,
                                    "y" : 5
                            },
                            "23" : {
                                    "x" : 2,
                                    "y" : 5
                            }
                    }
            }
    ],

并且将对每个文档都这样做。

对于您当前的结构,无法使用聚合框架进行转换,因为所有元素都是子文档,并且如果不明确命名每个元素就无法被聚合框架遍历

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2021-08-12
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多