[英]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" }
)
我得到什么? 我得到了每个文档看起来像的集合:
{
"_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.scores
或this.scores.score
而不是this.scores.map(a => a.score)
时,我拥有所有属性或 null 个值。
也许有人知道,我做错了什么?
您应该使用聚合而不是 MapReduce。这是来自官方 Mongo 文档的说明
聚合管道提供了比 map-reduce 更好的性能和更连贯的接口,并且可以使用聚合管道运算符重写各种 map-reduce 操作,例如 $group、$merge、$accumulator 等。
我用来获取聚合阶段的步骤:
结果是
[
{
'$match': {
'name': 'Aurelia Menendez'
}
}, {
'$unwind': {
'path': '$scores'
}
}, {
'$group': {
'_id': '$_id',
'total': {
'$sum': '$scores.score'
}
}
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.