如何解决按地图项分组并找到计数总和字段-Mongodb 3.6.9
我在下面的结构中有一个文档。
[{
"_id": 0001,"data": {
"status": {
"COMPLETED": [{
"count": 1.0,"assignee": "ABC"
},{
"count": 1.0,"assignee": "DEF"
}
],"OPEN": [{
"count": 5.0,"assignee": "XYZ"
},{
"count": 5.0,"assignee": "PQR"
}
]
},"assignee": {
"User1": [{
"count": 1.0,"status": "OPEN"
}
],"User2": [{
"count": 5.0,"status": "COMPLETED"
}
]
}
}
},{
"_id": 0002,"data": {
"status": {
"COMPLETED": [{
"count": 10.0,"assignee": "AAA"
},{
"count": 10.0,"assignee": "BBB"
}
],"OPEN": [{
"count": 50.0,"assignee": "CCC"
},{
"count": 50.0,"assignee": "DDD"
}
]
},"assignee": {
"User1": [{
"count": 10.0,"User2": [{
"count": 15.0,"status": "COMPLETED"
}
]
}
}
}
]
当按每个字段分组时,我们如何找到总数。 例如-
group by "status" should give result as;
=> COMPLETED = 22,OPEN = 110
group by "assignee" should give result as;
=> User1 = 11,User2 = 20
如果需要,我们可以通过将“状态”和“受让人”移出“数据”来简化文档。
解决方法
由于要按键分组,因此需要使用$objectToArray将它们转换为数组的值。您还可以将$map与$sum一起使用来对每个{{1}进行计数,然后使用$unwind来对它们进行全局$ group:
status
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。