首页 > 解决方案 > MongoDB加法和减法在聚合上不能同时工作

问题描述

我有这样的架构:

{
    "_id" : ObjectId("5c35f04c4e92b8337885d9a6"),
    "activity" : {
        "a": 10,
        "b": 20,
        "c": 30,
        "d": 40
    }
}

现在我想用一些乘法来执行加法和减法,因为我写了查询但是这个查询只在加法上工作正常,而不是减法。我的查询是这样的:

db.Collection.aggregate([
  { $match: { _id: ObjectId("5c35f04c4e92b8337885d9a6") } },
  { $unwind: "$_id" },
  {
    $project: {
      "activity.score": {
        $add: [
          {
            $multiply: [
              "$activity.a",
              0.5
            ]
          },
          {
            $multiply: [
              "$activity.b",
              0.5
            ]
          }
        ],
        $subtract: [
          {
            $multiply: [
              "$activity.c",
              0.2
            ]
          }
        ]
      }
    }
  }
])
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log(error);
  });

通过这个得到错误,即

'Invalid $project :: caused by :: an expression specification must contain exactly one field, the name of the expression.

如果我删除了减法部分,那么它工作正常。

任何人都可以建议我在哪里做错了。非常感谢任何帮助或建议

标签: mongodbaggregation

解决方案


推荐阅读