If-else conditional in $set operator

Hi @Najam_Ul_Sehar,

You can do it with single update query like this:

  • $set - to update points property.
  • $cond with $eq - to check if player is isCaptain property is equal to true.
  • $multiply - to multiply input points by 2 if player is captain.
db.collection.update({
  _id: 1
},
[
  {
    "$set": {
      "points": {
        "$cond": {
          "if": {
            "$eq": [
              "$isCaptain",
              true
            ]
          },
          "then": {
            "$multiply": [
              100,
              2
            ]
          },
          "else": 100
        }
      }
    }
  }
])

Working example

4 Likes