How can i calculate total positive ,total negative price and sum using Node.js and Mongoose

大兔子大兔子 提交于 2019-12-11 00:08:39

问题


i have written query for getting all user records

exports.index = function(req, res) {
    Userdata.find(function(err, userdatas) {
        if (err) {
            return handleError(res, err);
        }

        console.log(userdatas);

    });

};

console i am getting below documents

{
    "_id" : ObjectId("584bc9ba420a6b189c510af6"),
    "user_id" : 1,
    "price" : 2000.0,
    "type" : "credit",

},
{
    "_id" : ObjectId("584bc9ba420a6b189c510af7"),
    "user_id" : 1,
    "price" : -1000.0,
    "type" : "credit",

},
{
    "_id" : ObjectId("584bc9ba420a6b189c510af8"),
    "user_id" : 2,
    "price" : 1000.0,
    "type" : "credit",

}

now i want to calculate total positive ,total negative price and sum(total positive-total negative)

once this calculated i need to insert/update in summary collection

if user id already presented in summary collection that time we need to update the particular user document

if user id not present we need to create the new document for that user

here summary collection already user_id = 1 is present so we need to update this document and user_id = 2 not present in summary collection so we need to create .

    {
        "_id" : ObjectId("584bc9ba420a6b189c510af9"),
        "user_id": 1,
        "Totalpositiveprice": 3000.0,
        "Totalnegativeprice": 0,
        "Balanceprice": 3000.0
    },
{
        "_id" : ObjectId("584bc9ba420a6b189c510af9"),
        "user_id": 3,
        "Totalpositiveprice": 200.0,
        "Totalnegativeprice": -190,
        "Balanceprice": 10.0
    }

my expectation result:

    {
        "_id" : ObjectId("584bc9ba420a6b189c510af9"),
        "user_id": "1",
        "Totalpositiveprice": 5000.0,
        "Totalnegativeprice": -1000.0,
        "Balanceprice": 4000.0
    },
    {

        "user_id": "2",
        "Totalpositiveprice": 1000.0,
        "Totalnegativeprice": 0,
        "Balanceprice": 1000.0
    },
   {
        "_id" : ObjectId("584bc9ba420a6b189c510af9"),
        "user_id": 3,
        "Totalpositiveprice": 200.0,
        "Totalnegativeprice": -190,
        "Balanceprice": 10.0
    }

once this calculated i need to insert/update in summary collection


回答1:


Considering that expected results are numbers and the values from summary collection are numbers (otherwise you need to make them numbers) here is an aggregation that computes the result:

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()

Result:

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
}

Later you need to convert them to string if you need.

Note: The result it overrides the summary collection with new computed (and updated) values. Better test your resuls first.




回答2:


I am assuming that fields in your summaryCollection are numbers. you can loop through the userData and modify or create the user in the summary collection. I have added to your existing code:

exports.index = function(req, res) {
    Userdata.find(function(err, userdata) {
        if (err) {
            return handleError(res, err);
        }

        userdata.map(user => {
         //check if the user exists in summary collection
         SummaryCollection.findOne({user_id: user.user_id})
         .then(summaryUser => {
           if(summaryUser) {
             //check wheather to save positive or negative price
               if(user.price > 0) {
                 summaryUser.Totalpositiveprice + = user.price
              } else {
               summaryUser.Totalnegativeprice + = user.price
              }
              //modify all the other fields accorodingly
              return summaryUser.save();
            } else {
              //create new summary user and return summaryUser.save();
             }

          })
        })
        .then(savedSummary => {
         //you will have the modified summary object here 
         })

    });

};


来源:https://stackoverflow.com/questions/41119105/how-can-i-calculate-total-positive-total-negative-price-and-sum-using-node-js-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!