MongoDB加法和减法不能同时作用于聚合

xfyts7mz  于 2023-03-29  发布在  Go
关注(0)|答案(1)|浏览(169)

我的schema是这样的:

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

如果我去掉减法部分,那么它工作得很好。
任何人都可以建议我哪里做错了。任何帮助或建议真的很感激

jdzmm42g

jdzmm42g1#

{
    $project: {
      "activity.score": {
        $subtract: [{$add: [
          {
            $multiply: [
              "$activity.a",
              0.5
            ]
          },
          {
            $multiply: [
              "$activity.b",
              0.5
            ]
          }
        ]},
        {
            $multiply: [
              "$activity.c",
              0.2
            ]
          }
        ]
      }
    }

相关问题