如果除法值为零,则带有乘法和除法的Mongodb加法将不起作用

时间:2019-02-19 12:50:25

标签: mongodb aggregation

我有一个像这样的数据集:

{
    "_id" : ObjectId("5c35f04c4e92b8337885d9a6"),
    "activity" : {
        a: 10,
        b: 20,
        c: 30,
        d: 40,//This is for ratio purpose
        e: 50,//This is for ratio purpose
    }
}

现在我要进行乘法和除法运算 为此,我编写了查询,即

User.aggregate([
  { $match: { _id: ObjectId("5c35f04c4e92b8337885d9a6") } },
  { $unwind: "$_id" },
  {
    $project: {
      "activity.score": {
         $add: [
          {
            $multiply: [
              "$activity.message_count",
              1.5
            ]
          },
          {
            $multiply: [
              "$activity.b",
              1.6
            ]
          },
          {
            $multiply: [
              "$activity.c",
              1.7
            ]
          },
          {
            $multiply: [
              {
                $divide: [
                  "$activity.d",
                  "$activity.e"
                ]
              },
              1.8
            ]
          }
      }
    }
]).then(data => {
console.log(data)
})
.catch(error => {
console.log(error)
})

这样我得到了答案,但是当

  

d和e将变为0,即这样

{
        "_id" : ObjectId("5c35f04c4e92b8337885d9a6"),
        "activity" : {
            a: 10,
            b: 20,
            c: 30,
            d: 0,//This is for ratio purpose
            e: 0,//This is for ratio purpose
        }
    }

然后mongodb生成一个错误,该错误是 MongoError:不能用$除以零

任何人都可以建议我如何处理

0 个答案:

没有答案