gpt4 book ai didi

javascript - MongoDB - mapReduce

转载 作者:行者123 更新时间:2023-12-04 08:20:42 25 4
gpt4 key购买 nike

我有 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" }
)
我得到什么?我得到每个文档看起来像的集合:
  • “值”是数组:
  • {
    "_id": 20,
    "value": [42.17439799514388, 71.99314840599558, 81.23972632069464]
    }
  • “值”是值
  • {
    "_id": 188,
    "value": "060.314725741828,41.12327471818652,74.8699176311771"
    }
  • “值”是数组
  • {
    "_id": 193,
    "value": [47.67196715489599, 41.55743490493954, 70.4612811769744]
    }
    为什么我没有得到元素的总和?当我尝试时 this.scoresthis.scores.score而不是 this.scores.map(a => a.score) ,我有所有属性,或空值。
    也许有人有任何想法,我做错了什么?

    最佳答案

    您应该使用聚合而不是 MapReduce。这是来自官方 Mongo 文件的注释

    Aggregation pipeline provides better performance and a more coherentinterface than map-reduce, and various map-reduce operations can berewritten using aggregation pipeline operators, such as $group,$merge, $accumulator, etc..


    我用来获得聚合阶段的步骤:
  • 使用 MongoDB Compass 并打开聚合选项卡来测试聚合。
  • 添加阶段: $match :过滤学生, $unwind :压平分数数组, $group :通过总和获得所有分数。
  • 转换为代码

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

    MongoDB Compass Result

    关于javascript - MongoDB - mapReduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65513489/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com