如何填充映射减less的结果
TestSessionSchema.statics.getTopTesters = function(callback){ var o = {}; o.map = function(){ emit(this._customer, this.points); }; o.reduce = function(_customer, values){ var result = {_customer: _customer, sum_points: 0, }; values.forEach(function(point){ result.sum_points += point; }); return result; }; o.out = { replace: 'createdCollectionNameForResults' }; o.verbose = true; this.mapReduce(o,function(err, model, stats){ model.find().sort({'value.sum_points': "desc"}).limit(5).populate("_customer").exec(function(error, results){ log(results); }) }); }
在map-reduce部分,我正在创build_customers点。
model.find().sort({'value.sum_points': "desc"}).limit(5).populate("_customer")
不起作用
我该怎么做?
当您在MongoDB中执行mapReduce时,您必须确保您的emit值具有与您的reduce返回值相同的格式。
这意味着在你的情况下,如果map
调用emit(customer, points)
那么reduce
必须简单地返回points
的值。
要改变你的具体例子,你的map函数是可以的,但是你的reduce函数应该是:
reduce = function(_customer, values) { var result = 0; values.forEach(function(point){ result += point; }); return result; };
然后你的reduce函数将总结每个_customer的所有值(点),这就是你想要的。 输出将是_customer,指向字段名称为_id
和value
的键值对,其中value将是该_id(_customer)的所有点值的总和。
要查询结果,您将运行:
db.createdCollectionNameForResults.find().sort({value:-1}).limit(5)