Forudsat at værdierne i summary-collectionen virkelig er tal (konvertér dem først, hvis ikke), klarer én aggregasjon hele jobbet:
db.getCollection('userpricing').aggregate([ { $group: { _id: "$user_id", user_id: { $first: "$user_id" }, Totalpositiveprice: { $sum: { $cond: [ { '$gt': ['$price', 0] }, "$price", 0 ] } }, Totalnegativeprice: { $sum: { $cond: [ { '$lt': ['$price', 0] }, "$price", 0 ] } }, Balanceprice: { "$sum": "$price" } }}, { $lookup: { from: "summary", localField: "user_id", foreignField: "user_id", as: "user_id2" } }, { $project: { _id: 0, user_id: 1, Totalpositiveprice: { $sum: ["$Totalpositiveprice", { $sum: "$user_id2.Totalpositiveprice" }] }, Totalnegativeprice: { $sum: ["$Totalnegativeprice", { $sum: "$user_id2.Totalnegativeprice" }] }, Balanceprice: { $sum: ["$Balanceprice", { $sum: "$user_id2.Balanceprice" }] } }}, { $out: "summary" } ]).pretty() Resultat:
db.summary.find().pretty() { "_id" : ObjectId("584fde2906c7385883be0d15"), "user_id" : 2, "Totalpositiveprice" : 10000, "Totalnegativeprice" : 0, "Balanceprice" : 10000 } { "_id" : ObjectId("584fde2906c7385883be0d16"), "user_id" : 1, "Totalpositiveprice" : 23000, "Totalnegativeprice" : -10000, "Balanceprice" : 13000 } Konvertér tallene til strenge bagefter, hvis dit outputformat kræver det.
Bemærk: stage $out erstatter summary-collectionen med de nyligt beregnede værdier. Test først på en kopi.