如何在MongoDB中使用map reduce求平均值?

时间:2019-01-03 09:47:55

标签: mongodb mapreduce

我的文档格式:

{
  "PItems": {
    "Workspaces": [
      {
        "Key": "Item1",
        "Size": 228.399,
        "Foo": "bar"
      },
      {
        "Key": "Item2",
        "Size": 111.399,
        "Bar": "baz"
      },
      {
        "Key": "Item2",
        "Size": 636.66,
        "Baz": "foo"
      }

    ]
  }
}

我需要从集合中的所有文档中找到每个项目的平均大小。我该怎么办?

预期输出:

项目1:346.12

第2项:563.58

我尝试了以下方法:

db.Resources.mapReduce(
  function() { 
    this.PItems.Workspaces.forEach(
       function(z) {
          emit(z.Key, z.Size);
       }
    );
  },
  function(item, space) {
    var total = 0;
    for ( var i=0; i<space.length; i++ )
        total += size[i];
    return { avg : total/space.length };
  },
  out: { inline: 1 }
);

参数列表后出现语法错误:SyntaxError:缺少)。我在这里想念什么?

0 个答案:

没有答案
相关问题