如何用MongoDB的$accumulator按性别统计数量?代码异常排查
问题排查与代码修正
错误点分析
你的代码存在三个关键问题,导致统计值全部为0:
- 未执行赋值操作:
state.maleCount+ 1、state.count + 1这类写法仅计算了数值,却没有将结果赋值回原变量,因此统计值始终保持初始化的0。 - 变量名拼写错误:第二个判断条件中使用了未定义的
type变量,正确变量应为gender。
修正后的代码
db.collection.aggregate([ { $match: { department: "Finance" } }, { $group: { _id: "$department", count: { $sum: 1 }, data: { $accumulator: { init: function() { return { count: 0, maleCount: 0, femaleCount: 0 } }, accumulate: function(state, gender) { if (gender === "Male") { state.maleCount += 1; // 修正:添加赋值操作 } if (gender === "Female") { // 修正:变量名从type改为gender state.femaleCount += 1; // 修正:添加赋值操作 } state.count += 1; // 修正:添加赋值操作 return state; }, accumulateArgs: ["$user.gender"], merge: function(state1, state2) { return { count: state1.count + state2.count, maleCount: state1.maleCount + state2.maleCount, femaleCount: state1.femaleCount + state2.femaleCount } }, finalize: function(state) { return state; }, lang: "js" } } } } ])
验证结果
运行修正后的代码,会得到你期望的输出:
{ "_id" : "Finance", "count" : 3, "data" : { "count" : 3, "maleCount" : 2, "femaleCount" : 1 } }
内容的提问来源于stack exchange,提问作者Balasubramanian S
相关产品推荐
相关产品推荐

