繁体   English   中英

MongoDB - mapReduce

[英]MongoDB - mapReduce

我有 mongoDB 集合,其中每个文档如下所示:

{
    "_id": 1,
    "name": "Aurelia Menendez",
    "scores": [{
        "score": 60.06045071030959,
        "type": "exam"
    }, {
        "score": 52.79790691903873,
        "type": "quiz"
    }, {
        "score": 71.76133439165544,
        "type": "homework"
    }]
}

我尝试运行:

db.students.mapReduce(
    function() {
        emit(this._id, this.scores.map(a => a.score));
     },
     function(_id, values) {
        //here i try:
        1) return values.reduce((a, b) => a + b);
        2) return values.reduce((a, b) => a + b, 0);
        3) return Array.sum(values);
     },
    { out: "total_scores" }
 )

我得到什么? 我得到了每个文档看起来像的集合:

  1. “值”是数组:
{
    "_id": 20,
    "value": [42.17439799514388, 71.99314840599558, 81.23972632069464]
}
  1. “价值”就是价值
{
    "_id": 188,
    "value": "060.314725741828,41.12327471818652,74.8699176311771"
}
  1. “值”是数组
{
    "_id": 193,
    "value": [47.67196715489599, 41.55743490493954, 70.4612811769744]
}

为什么我没有得到元素的总和? 当我尝试this.scoresthis.scores.score而不是this.scores.map(a => a.score)时,我拥有所有属性或 null 个值。

也许有人知道,我做错了什么?

您应该使用聚合而不是 MapReduce。这是来自官方 Mongo 文档的说明

聚合管道提供了比 map-reduce 更好的性能和更连贯的接口,并且可以使用聚合管道运算符重写各种 map-reduce 操作,例如 $group、$merge、$accumulator 等。

我用来获取聚合阶段的步骤:

  1. 使用 MongoDB Compass 并打开聚合选项卡来测试聚合。
  2. 添加阶段:$match:过滤学生,$unwind:压平分数数组,$group:将所有分数相加得到总分。
  3. 转换为代码

结果是

[
  {
    '$match': {
      'name': 'Aurelia Menendez'
    }
  }, {
    '$unwind': {
      'path': '$scores'
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'total': {
        '$sum': '$scores.score'
      }
    }
  }
]

MongoDB 指南针结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM