繁体   English   中英

MongoDB 嵌套组聚合

[英]MongoDB nested groups aggregation

我在 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" : [] } ] } ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM