below is my userpricing collection data
{
\"_id\" : ObjectId(\"584bc9ba420a6b189c510af6\"),
\"user_id\" : 1,
\"mobilenumber\":\"01234\",
\"p
As from other answers, the problem with $out is that it will replace the summary collection if one exists and you may not want that. You can use a little JavaScript for that.
var cursor = db.userpricing.aggregate([
{
$group : {
_id : "$user_id",
Totalpositiveprice : {
$sum : {
$cond : {
if: { $gte : ["$price" , 0]},
then : "$price",
else : 0
}
}
},
Totalnegativeprice : {
$sum : {
$cond : {
if: {$lte : ["$price" , 0]},
then : "$price",
else : 0
}
}
},
Balanceprice : {$sum : "$price"}
}
},
{
$project : {
_id : 0,
user_id : "$_id",
Totalpositiveprice : 1,
Totalnegativeprice : 1,
Balanceprice : 1
}
}
]);
while(cursor.hasNext()) {
var elem = cursor.next();
db.summary.update(
{user_id : elem.user_id},
elem,
{upsert : true}
);
}
> db.summary.find()
{ "_id" : ObjectId("58564bb71e2cb47f2ddcf1b4"), "Totalpositiveprice" : 10000, "Totalnegativeprice" : 0, "Balanceprice" : 10000, "user_id" : 2 }
{ "_id" : ObjectId("58564bb71e2cb47f2ddcf1b5"), "Totalpositiveprice" : 20000, "Totalnegativeprice" : -10000, "Balanceprice" : 10000, "user_id" : 1 }