Home > Software engineering >  Using add operator in set pipeline
Using add operator in set pipeline

Time:08-01

I m trying to update some record using $add operator and $set

Example

[
  {
    "key": 1,
    "revenue": 0
  },
  {
    "key": 2,
    "revenue": 0
  }
]

Query

db.collection.update({
  "key": 2
},
{
  $set: {
    revenue: {
      $add: [
        "$revenue",
        7
      ]
    }
  }
},
{
  "upsert": false
})

What I am trying to do is update revenue on every request to update by summing new value with previous value

What am i missing

Output

{
    "_id": ObjectId("5a934e000102030405000001"),
    "key": 2,
    "revenue": {
      "$add": [
        "$revenue",
        7
      ]
    }
  }
]

CodePudding user response:

You are missing [] to create a pipeline which is needed in order to use the current value of revenue. This will work:

db.collection.update({
  "key": 2
},
[
  {
    $set: {
      revenue: {
        $add: [
          "$revenue",
          7
        ]
      }
    }
  }
],
{
  "upsert": false
})

See how it works on the playground example

  • Related