How can i calculate price positive and negative price using mongodb or robomongo?

前端 未结 4 638
感动是毒
感动是毒 2020-12-20 08:41

below is my userpricing collection data

{
    \"_id\" : ObjectId(\"584bc9ba420a6b189c510af6\"),
    \"user_id\" : 1,
    \"mobilenumber\":\"01234\",
    \"p         


        
4条回答
  •  误落风尘
    2020-12-20 09:45

    You can do it by using conditional sum and export in another collection use $out: collectionName

    can try it :

    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"}}
         },
         {$project: {_id:0, user_id:1, Totalpositiveprice:1, Totalnegativeprice:1, Balanceprice:1}},
         {$out: "summary"}
    ])
    

    N.B: result exported in summary collection

提交回复
热议问题