【发布时间】:2020-01-20 07:51:03
【问题描述】:
请,我需要帮助来汇总 MongoDb 嵌套文档中的状态(2 和 3)计数。
我的 Json:
[
{
"_id":1,
"name":"aaa",
"calendars":[
{
"year":2012,
"status":2
},
{
"year":2013,
"status":1
},
{
"year":2014,
"status":3
}
]
},
{
"_id":2,
"name":"bbb",
"calendars":[
{
"year":2012,
"status":1
},
{
"year":2013,
"status":1
},
{
"year":2014,
"status":2
}
]
}
]
这是我的 mongodb 代码:
db.mycol.aggregate([{"$match": {"calendars.status": {"$in": [2, 3]}}}, {"$unwind": "$calendars"},
{"$group": {_id: {"year": "$calendars.year"},
total: {"$sum": 1}
}},
{"$project": {
"year": "$_id.year",
"total": "$total", "_id": 0}},
])
我需要结果:
year total
2012 1
2013 0
2014 2
谢谢
【问题讨论】:
-
在
$unwindmongoplayground.net/p/j1wA7rYntfM之后再放一个$match阶段 -
您的文档是作为数组插入的吗?