[英]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.