below is my userpricing collection data
{
\"_id\" : ObjectId(\"584bc9ba420a6b189c510af6\"),
\"user_id\" : 1,
\"mobilenumber\":\"01234\",
\"p
Whatever you want to do involves a complex query. See the below query. Let me explain it first.
1- first pipeline $group
is obvious to you.
2- second pipeline $lookup
is required to generate your desired result as you want that the current prices and the already summarized prices should be compiled into one document.
3- third stage is just unwinding the array summary
we have looked up so that we will be able to compile the prices.
4- fourth $project
stage is doing what you really want to do that is to say that it is compiling the summary document you will be able to understand it.
5- generating the summary collection.
db.getCollection('userpricing').aggregate([
{$group:{
_id:"$user_id",
Totalpositiveprice:{$sum:{$cond:{if:{ $gt:["$price",0]}, then: "$price", else: 0}}},
Totalnegativeprice:{$sum:{$cond:{if:{ $lt:["$price",0]}, then: "$price", else: 0}}},
Balanceprice:{"$sum":"$price"}
}},
{
$lookup:
{
from: "summary",
localField: "_id",
foreignField: "user_id",
as: "summary"
}
},
{$unwind:{path:"$summary", preserveNullAndEmptyArrays:true}},
{$project:{
_id:0,
user_id:"$_id",
Balanceprice:{$add:["$Balanceprice", {$cond:{if:{ $eq:["$summary",undefined]}, then: 0, else: "$summary.Balanceprice"}}]},
Totalnegativeprice:{$add:["$Totalnegativeprice", {$cond:{if:{ $eq:["$summary",undefined]}, then: 0, else: "$summary.Totalnegativeprice"}}]},
Totalpositiveprice:{$add:["$Totalpositiveprice", {$cond:{if:{ $eq:["$summary",undefined]}, then: 0, else: "$summary.Totalpositiveprice"}}]}
}},
{$out:"summary"}
])