我正在尝试使用mapReduce方法来计算住在特定区域的男性和女性的数量。我正在使用以下代码,然后我编写一个逻辑来计算值。想知道是否可以在模块内完成。这是可能的还是我现有的方法是这样做的方式
module.export.findStudentsForGivenAdministrativeAreaInAState = function(administrativeArea){
var o = {};
var self = this;
o.map = function () {
var values = {gender:this.gender,area_level_2:this.address.administrative_area_level_2};
emit(this._id, values)
};
o.reduce = function (k, vals) {
return vals;
};
o.query = {
'address.administrative_area_level_1': administrativeArea
};
return new Promise.resolve(Student.mapReduce(o))
.then(function (data) {
return data;
}).catch(function (error) {
routesLogger.logError("studentDAL", "getDistinctStatesWhereStudentsAreRegistered", error);
return error;
});
};
答案 0 :(得分:0)
这也可以使用 aggregation framework 来完成,因为聚合在服务器(C ++)中本地运行,所以性能更好,而mapReduce会生成单独的javascript线程来运行JavaScript码。因此,您可以运行以下 aggregation
管道以获得相同的结果:
var Student = require('../../../models/Student');
module.exports.findStudentsForGivenAdministrativeAreaInAState = function(administrativeArea, callback){
var pipeline = [
{
"$match": { "address.administrative_area_level_1": administrativeArea }
},
{
"$group": {
"_id": "$address.administrative_area_level_2",
"men": {
"$sum": {
"$cond": [ { "$eq": [ "$gender", "male" ] }, 1, 0 ]
}
},
"women": {
"$sum": {
"$cond": [ { "$eq": [ "$gender", "female" ] }, 1, 0 ]
}
},
"count": { "$sum": 1 }
}
}
];
Student.aggregate(pipeline, function (err, results) {
if(err) { callback(err); }
else {
console.log(results);
callback(null, results);
};
});
};