【问题标题】:How can i calculate total positive ,total negative price and sum using Node.js and Mongoose我如何使用 Node.js 和 Mongoose 计算总正价、总负价和总和
【发布时间】:2017-04-28 09:30:43
【问题描述】:

我已经编写了获取所有用户记录的查询

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

        console.log(userdatas);

    });

};

控制台我正在获取以下文档

{
    "_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",

}

现在我想计算总正数、总负数价格和总和(总正数-总负数)

计算后我需要在摘要集合中插入/更新

如果用户 id 已经出现在摘要集合中,那么我们需要更新特定的用户文档

如果用户 ID 不存在,我们需要为该用户创建新文档

这里的摘要集合已经存在 user_id = 1,因此我们需要更新此文档,并且 user_id = 2 不存在于摘要集合中,因此我们需要创建。

    {
        "_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
    }

我的预期结果:

    {
        "_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
    }

计算后我需要在摘要集合中插入/更新

【问题讨论】:

  • 注意:在预期结果中,值是错误的,应该是正23000,负-10000,user_id 1的余额13000?

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

我假设您的 summaryCollection 中的字段是数字。您可以遍历 userData 并在摘要集合中修改或创建用户。我已添加到您现有的代码中:

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

    });

};
【解决方案2】:

考虑到预期结果是数字,summary 集合中的值是数字(否则您需要将它们设为数字),这是一个计算结果的聚合:

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

结果:

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
}

如果需要,稍后您需要将它们转换为字符串。

注意: 它用新的计算(和更新)值覆盖汇总集合的结果。 最好先测试你的结果。

【讨论】:

  • 我只是测试它,它有效。但它假定所有值都是数字,而不是字符串。您需要先将它们转换为数字才能计算它们。
  • 正如我所说,代码有效。您还需要 user_id 是一个数字,以便在其他集合中进行查找匹配。
  • 如果用户 id 3 已经存在,如果我运行此代码“user_id”:3 被删除
猜你喜欢
  • 2019-06-09
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
相关资源
最近更新 更多