我的mongo-db中输入了以下数据:
[
{
"year": "2022-10-01",
"Area": "abc",
"Engineering": 100,
"Commerce": 20,
"Arts": 10
},
{
"year": "2022-10-01",
"Area": "def",
"Engineering": 90,
"Commerce": 60,
"Arts": 40
},
{
"year": "2021-01-01",
"Area": "abc",
"Engineering": 70,
"Commerce": 30,
"Arts": 90
},
{
"year": "2022-01-01",
"Area": "def",
"Engineering": 100,
"Commerce": 10,
"Arts": 50
}
]根据每个地区的最终结果,有几年的记录将以这种形式进行,首先按日期分组,然后在每个部门的每个区域和范围内按区域分组。
结果:
{
"2022-10-01": {
"abc": {
"Engineering": "<total engineering count>",
"Commerce": "<total commerce count>",
"Arts": "<total arts count>"
},
"def": {
"Engineering": "<total engineering count>",
"Commerce": "<total commerce count>",
"Arts": "<total arts count>"
}
},
"2021-01-01": {
"abc": {
"Engineering": "<total engineering count>",
"Commerce": "<total commerce count>",
"Arts": "<total arts count>"
},
"def": {
"Engineering": "<total engineering count>",
"Commerce": "<total commerce count>",
"Arts": "<total arts count>"
}
}
}发布于 2022-06-06 12:29:45
查询
year,area分组并与计数相加$arrayToObject 2倍*字段上的数据使mongodb中的事情变得很困难,如果没有它们,查询将仅仅是前两个简单组
aggregate(
[{"$group":
{"_id": {"year": "$year", "Area": "$Area"},
"Engineering": {"$sum": "$Engineering"},
"Commerce": {"$sum": "$Commerce"},
"Arts": {"$sum": "$Arts"}}},
{"$group":
{"_id": "$_id.year",
"docs":
{"$push":
{"k": "$_id.Area",
"v":
{"Engineering": "$Engineering",
"Commerce": "$Commerce",
"Arts": "$Arts"}}}}},
{"$replaceRoot":
{"newRoot":
{"$arrayToObject":
[[{"k": "$_id", "v": {"$arrayToObject": ["$docs"]}}]]}}},
{"$group": {"_id": null, "docs": {"$mergeObjects": "$$ROOT"}}},
{"$replaceRoot": {"newRoot": "$docs"}}])https://stackoverflow.com/questions/72516932
复制相似问题