【发布时间】:2020-10-30 09:38:38
【问题描述】:
我在 mongodb 中有一组数据,如下所示:
{_id: ObjectId(""), created: date, otherObjectId: ObjectId(""), amount: number}
是否可以按年、按月、然后按 otherCollectionID 编写聚合?像这样的:
[{year: [{month: [{otherCollectionID: {amount: "$amount"}}]}
我可以按年和月汇总,但我不确定如何为第二个对象 ID 字段添加另一个组。
db.Collection.aggregate([
{$match: {status: 'succeeded'}},
{
$group: {
_id: {
year: {"$year": '$created'},
month: {"$month": '$created'},
otherObjectId: "$otherObjectId"
},
count: {$sum: 1},
amount: {$sum: '$amount'}
}
},
{
$group: {
_id: "$_id.year",
"data": {
$push: {
month: "$month",
count: "$count",
amount: "$amount"
}
}
}
}
])
这样的结果是:
{
"_id" : 2020,
"data" : [
{
"count" : 4,
"amount" : 200
},
{
"count" : 1,
"amount" : 50
},
... for other months
]
}
【问题讨论】:
-
您能添加您的预期结果吗?
标签: javascript node.js mongodb mongodb-query aggregation-framework