MongoDB update with condition

You can't.

Mongo doesn't support combining fields, conditionals etc. in the update statement.


See https://stackoverflow.com/a/56551655/442351 below.


We can do it using aggregation pipeline. Here i am updating male to female and female to male.

db.customer.updateMany(
   { },
   [
     { $set: { gender: { $switch: {
                           branches: [
                               { case: { $eq: [ "$gender", 'male' ] }, then: "female" },
                               { case: { $eq: [ "$gender", 'female' ] }, then: "male" }
                           ],
                           default: ""
     } } } }
   ]
)

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:

// { a: "Hello", b: "World" }
// { a: "Olleh", b: "Dlrow" }
db.collection.updateMany(
  {},
  [ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ]
)
// { a: "Hello", b: "World", active: true  }
// { a: "Olleh", b: "Dlrow", active: false }
  • The first part {} is the match query, filtering which documents to update (in our case all documents).

  • The second part [ { $set: { active: { $eq: [ "$a", "Hello" ] } } } ] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields. Then any aggregation operator can be used within the $set stage; in our case a conditional equality check on which depends the value to use for the new active field.