0
0
MongoDBquery~5 mins

Upsert behavior (update or insert) in MongoDB

Choose your learning style9 modes available
Introduction

Upsert lets you update a record if it exists or add it if it doesn't. This saves time by doing both in one step.

When you want to add a new user or update their info if they already exist.
When syncing data from another system and you want to avoid duplicates.
When saving settings that might be new or changed.
When logging events and you want to update counts or create new entries.
Syntax
MongoDB
db.collection.updateOne(
  <filter>,
  <update>,
  { upsert: true }
)

filter finds the document to update.

update describes the changes to make.

upsert: true means insert if no match is found.

Examples
Update Alice's age to 30 or add Alice if she doesn't exist.
MongoDB
db.users.updateOne(
  { username: "alice" },
  { $set: { age: 30 } },
  { upsert: true }
)
Increase stock by 10 for product 12345 or add it if missing.
MongoDB
db.products.updateOne(
  { sku: "12345" },
  { $inc: { stock: 10 } },
  { upsert: true }
)
Sample Program

This code updates Bob's email if he exists or adds a new user Bob with that email. Then it shows Bob's record.

MongoDB
use testdb

// Try to update a user named 'bob' or insert if not found
 db.users.updateOne(
   { username: "bob" },
   { $set: { email: "bob@example.com" } },
   { upsert: true }
 )

// Find and show the user 'bob'
 db.users.find({ username: "bob" }).toArray()
OutputSuccess
Important Notes

If multiple documents match the filter, only one is updated.

Without upsert: true, no new document is created.

Use $set to change fields without replacing the whole document.

Summary

Upsert updates a document if found or inserts it if missing.

Use updateOne or updateMany with upsert: true.

This helps keep data consistent with fewer commands.