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.
Jump into concepts and practice - no test required
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.
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.
db.users.updateOne(
{ username: "alice" },
{ $set: { age: 30 } },
{ upsert: true }
)db.products.updateOne(
{ sku: "12345" },
{ $inc: { stock: 10 } },
{ upsert: true }
)This code updates Bob's email if he exists or adds a new user Bob with that email. Then it shows Bob's record.
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()
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.
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.
upsert option do in a MongoDB updateOne operation?updateOne in MongoDB?users with documents:{ _id: 1, name: "Alice", age: 25 }db.users.updateOne({ _id: 2 }, { $set: { name: "Bob", age: 30 } }, { upsert: true })db.users.find().toArray()?db.products.updateOne({ sku: "123" }, { price: 19.99 })status field to "active" for a user with email: "user@example.com". If no such user exists, insert a new document with email and status. Which MongoDB command correctly achieves this?