简体   繁体   中英

MongoDB nested groups aggregation

I have a set of data in mongodb that looks like this:

{_id: ObjectId(""), created: date, otherObjectId: ObjectId(""), amount: number}

Is it possible to write an aggregation by year, then by month, then by otherCollectionID? Something like this:

[{year: [{month: [{otherCollectionID: {amount: "$amount"}}]}

I am able to aggregate by year and month, but I am not sure how to add another group for the second object ID field.

 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" } } } } ])

The result of this is:

 { "_id" : 2020, "data" : [ { "count" : 4, "amount" : 200 }, { "count" : 1, "amount" : 50 }, ... for other months ] }

I actually got it after reading the mongo documentation a little further. Here is my query:

 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 }} ])

This will result in:

 "_id" : { "year" : 2015, "month" : 12 }, "data" : [ { "count" : 7, "amount" : 70, "otherData" : [] } ] } { "_id" : { "year" : 2016, "month" : 1 }, "data" : [ { "count" : 27, "amount" : 10000, "otherData" : [] } ] } ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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