Upsert

Reference type:Cheat sheetFormat:Syntax + example + use case

Reference group: Update operator families

What it does

Inserts when no document matches; otherwise updates a match.

Syntax

{ upsert: true } option

Use case

Create-or-update preferences.

Important notes

Use a unique index for intended identity.

Upsert: practical example
db.userPreferences.updateOne({ userId }, { $set: { theme: "dark" }, $setOnInsert: { createdAt: new Date() } }, { upsert: true })
💡 Explanation Inserts when no document matches; otherwise updates a match. When to use it Create-or-update preferences. Caution Use a unique index for intended identity.
Key Takeaways
  • Inserts when no document matches; otherwise updates a match.
  • Typical use: Create-or-update preferences.