如何解决MongoDB嵌套组聚合
我在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
]
}
解决方法
在进一步阅读mongo文档后,我实际上得到了它。这是我的查询:
db.Collection.aggregate([
{ $lookup: {
from: "OtherCollection",localField: "otherObjectId",foreignField: "_id",as: "otherData"
}},{ $unwind: "$otherData" },{ $project: {
"_id": 1,"created": 1,"amount": 1,"otherObjectId": 1,"otherData.field": 1
}},{ $group: {
_id: {
year: {"$year": '$created'},month: {"$month": '$created'},},otherData: {
$addToSet: "$otherData"
},count: {$sum: 1},amount: {$sum: '$amount'}
}
},{ $group: {
_id: {year: "$_id.year",month: "$_id.month"},data: {
$push: {
count: "$count",amount: "$amount",otherData: "$otherData"
}
}
}
},{ $sort: {
"_id.year": 1,"_id.month": 1
}}
])
这将导致:
"_id" : {
"year" : 2015,"month" : 12
},"data" : [
{
"count" : 7,"amount" : 70,"otherData" : []
}
]
}
{
"_id" : {
"year" : 2016,"month" : 1
},"data" : [
{
"count" : 27,"amount" : 10000,"otherData" : []
}
]
}
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。