querydrill

Learn ›MongoDB fundamentals ›Updating documents

Upsert: insert or update

updateupsert$set

An upsert is “update, or insert if there was nothing to update”. It is one operation, so it does not have the race condition that a find-then-insert has - which is the reason to use it, not the convenience.

db.users.updateOne(
  {
    email: "denish@example.com"
  },
  {
    $set: {
      name: "Denish"
    }
  },
  {
    upsert: true
  }
)

Meaning:

If document exists
    → update it

If it doesn't exist
    → insert it

Useful in:

Practise this

1 exercise