MongoDB:如何对$addFields生成的字段求和?计算2022年1月全文档总和
MongoDB聚合求和错误修正方案
问题原因
你在$group阶段引用的字段名错误:$addFields创建的字段是cases_total_months|202201,但你在$group里写的是$cases_total_months|20220101——这个字段根本不存在,MongoDB会将不存在的字段视为0,所以最终求和结果为0。
修正后的基础查询
将$group中的字段名修正为正确的cases_total_months|202201即可得到预期结果:
db.collection.aggregate([ { "$match": { "account": { "$in": ["a", "b"] } } }, { "$addFields": { "cases_total_months|202201": { "$sum": [ "$cases_total_date.20220101", "$cases_total_date.20220102", "$cases_total_date.20220103" ] } } }, { "$group": { "_id": "", "cases_total_months|202201_all": { "$sum": "$cases_total_months|202201" } } } ])
执行后会得到预期结果:
[ { "_id": "", "cases_total_months|202201_all": 42 } ]
更灵活的优化方案(无需手动列举日期)
如果cases_total_date下的日期字段较多,手动列举效率低,可以用$objectToArray将嵌套对象转为数组,再过滤出2022年1月的日期,最后求和:
db.collection.aggregate([ { "$match": { "account": { "$in": ["a", "b"] } } }, { "$addFields": { "jan2022_cases": { "$sum": { "$map": { "input": { "$objectToArray": "$cases_total_date" }, "as": "item", "in": { "$cond": [ { "$regexMatch": { "input": "$$item.k", "regex": "^202201" } }, "$$item.v", 0 ] } } } } } }, { "$group": { "_id": "", "total_jan2022": { "$sum": "$jan2022_cases" } } } ])
这个方法会自动匹配所有以202201开头的日期字段,无需手动添加,扩展性更强。
内容的提问来源于stack exchange,提问作者venv
相关产品推荐
相关产品推荐

