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

前端 未结 4 643
感动是毒
感动是毒 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:47

    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 }
    

提交回复
热议问题