在MongoDB中使用$ subtract对象数组

时间:2018-01-02 10:14:43

标签: mongodb aggregation-framework

考虑集合

{   "name": "Student1",   "marks": [
    {
      "subject": "Subject1",
      "marks": 12
    },
    {
      "subject": "Subject2",
      "marks": 15
    },
    {
      "subject": "Subject3",
      "marks": 20
    }   ] }

我正在尝试对商标执行$减法。我尝试了如下聚合。

db.mycoll.aggregate(
[
      {
        "$addFields": {
          diff: {$subtract:["$marks.0.marks","$marks.1.marks","$marks.2.marks"]}
        }
      }
    ]
)

这种做法似乎没有奏效。我收到了错误

"Couldn't execute query: cant $subtract a array from a array"

1 个答案:

答案 0 :(得分:0)

您应该能够利用 $reduce 运算符来实现所需的输出,如下所示:

db.mycoll.aggregate([
    {
        "$addFields": {
            "diff": { 
                "$reduce": { // expression returns difference
                    "input": "$marks",
                    "initialValue": 0,
                    "in": { "$subtract": ["$$this.marks", "$$value"] }
                }
            }
        }
    }
])