Bird
Raised Fist0
MongoDBquery~10 mins

Upsert behavior (update or insert) in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Upsert behavior (update or insert)
Receive upsert request
Search for document matching filter
Found?
YesUpdate document
Insert new document
Return result
The database checks if a document matches the filter. If yes, it updates it; if no, it inserts a new document.
Execution Sample
MongoDB
db.collection.updateOne(
  { name: "Alice" },
  { $set: { age: 30 } },
  { upsert: true }
)
This command updates Alice's age to 30 if she exists; otherwise, it inserts a new document with name Alice and age 30.
Execution Table
StepActionFilter Search ResultUpdate or InsertResult
1Search for document with {name: 'Alice'}No document foundInsert new document {name: 'Alice', age: 30}Document inserted
2Return operation result--Upsert completed with insert
💡 No matching document found, so a new document was inserted.
Variable Tracker
VariableStartAfter Step 1After Step 2
Document in collection[{name: 'Bob', age: 25}][{name: 'Bob', age: 25}, {name: 'Alice', age: 30}][{name: 'Bob', age: 25}, {name: 'Alice', age: 30}]
Key Moments - 2 Insights
Why does the database insert a new document instead of updating?
Because the filter {name: 'Alice'} did not find any existing document (see execution_table step 1), so upsert inserts a new one.
What happens if a matching document is found?
The database updates the existing document with the new values instead of inserting (not shown in this trace but implied by the flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the filter search result at step 1?
ANo document found
BError occurred
CDocument found
DMultiple documents found
💡 Hint
Check the 'Filter Search Result' column in execution_table row 1.
At which step does the database insert a new document?
AStep 2
BStep 1
CNo insertion happens
DAfter step 2
💡 Hint
Look at the 'Update or Insert' column in execution_table row 1.
If the collection already had a document with name 'Alice', what would change in the execution table?
AFilter search result would be 'No document found' and insert happens
BNo change, insert always happens
CFilter search result would be 'Document found' and update happens
DOperation would fail
💡 Hint
Refer to the concept_flow where update happens if document is found.
Concept Snapshot
Upsert in MongoDB:
Use updateOne() with upsert:true option.
If filter matches a document, update it.
If no match, insert new document.
Prevents duplicate inserts and ensures data is updated or created.
Full Transcript
Upsert behavior in MongoDB means the database tries to find a document matching the filter. If it finds one, it updates that document with the new data. If it does not find any matching document, it inserts a new document with the given data. This is done using updateOne() or updateMany() with the option upsert:true. The execution flow starts by searching for the document. If found, it updates; if not, it inserts. This prevents duplicates and ensures data is either updated or created as needed.

Practice

(1/5)
1. What does the upsert option do in a MongoDB updateOne operation?
easy
A. It only inserts a new document without updating existing ones.
B. It updates a document if it exists, or inserts a new one if it does not.
C. It deletes a document if it exists, otherwise does nothing.
D. It duplicates the document regardless of existence.

Solution

  1. Step 1: Understand the upsert option

    The upsert option in MongoDB means update if found, insert if not found.
  2. Step 2: Apply to updateOne operation

    When using updateOne with upsert: true, MongoDB updates the matching document or inserts a new one if none matches.
  3. Final Answer:

    It updates a document if it exists, or inserts a new one if it does not. -> Option B
  4. Quick Check:

    Upsert = update or insert [OK]
Hint: Upsert means update if found, else insert new [OK]
Common Mistakes:
  • Thinking upsert only inserts without updating
  • Confusing upsert with delete operation
  • Assuming upsert duplicates documents
2. Which of the following is the correct syntax to perform an upsert using updateOne in MongoDB?
easy
A. db.collection.updateOne(filter, update, {update: true})
B. db.collection.updateOne(filter, update, {insert: true})
C. db.collection.updateOne(filter, update, {upsert: true})
D. db.collection.updateOne(filter, update, {replace: true})

Solution

  1. Step 1: Recall the updateOne method parameters

    The updateOne method takes a filter, an update document, and an options object.
  2. Step 2: Identify the correct option for upsert

    The option to enable upsert is {upsert: true}, which tells MongoDB to insert if no match is found.
  3. Final Answer:

    db.collection.updateOne(filter, update, {upsert: true}) -> Option C
  4. Quick Check:

    Use upsert: true in options [OK]
Hint: Use {upsert: true} in updateOne options [OK]
Common Mistakes:
  • Using {insert: true} instead of {upsert: true}
  • Omitting the options object entirely
  • Confusing update with replace option
3. Given the collection users with documents:
{ _id: 1, name: "Alice", age: 25 }
What will be the result after running:
db.users.updateOne({ _id: 2 }, { $set: { name: "Bob", age: 30 } }, { upsert: true })

and then querying db.users.find().toArray()?
medium
A. [{ _id: 1, name: "Alice", age: 25 }, { _id: 2, name: "Bob", age: 30 }]
B. [{ _id: 1, name: "Alice", age: 25 }]
C. [{ _id: 2, name: "Bob", age: 30 }]
D. []

Solution

  1. Step 1: Understand the updateOne with upsert

    The filter looks for _id: 2, which does not exist, so upsert inserts a new document with _id: 2 and the given fields.
  2. Step 2: Check existing documents

    The original document with _id: 1 remains unchanged, so the collection now has two documents.
  3. Final Answer:

    [{ _id: 1, name: "Alice", age: 25 }, { _id: 2, name: "Bob", age: 30 }] -> Option A
  4. Quick Check:

    Upsert inserts missing document, keeps existing [OK]
Hint: Upsert inserts new if filter misses existing docs [OK]
Common Mistakes:
  • Assuming existing documents get deleted
  • Thinking upsert only updates existing documents
  • Expecting only the new document after upsert
4. You run the following code but it does not insert a new document when no match is found:
db.products.updateOne({ sku: "123" }, { price: 19.99 })

What is the likely error?
medium
A. The filter syntax is incorrect and causes a syntax error.
B. MongoDB does not support upsert with updateOne.
C. The update document is missing the $set operator.
D. Missing the upsert: true option in the updateOne call.

Solution

  1. Step 1: Check the updateOne parameters

    The updateOne call lacks the options object with upsert: true, so it only updates existing documents.
  2. Step 2: Confirm upsert behavior

    Without upsert: true, no new document is inserted if the filter finds no match.
  3. Final Answer:

    Missing the upsert: true option in the updateOne call. -> Option D
  4. Quick Check:

    Upsert option needed to insert new docs [OK]
Hint: Add {upsert: true} to updateOne options to insert [OK]
Common Mistakes:
  • Forgetting to add upsert option
  • Confusing missing $set with upsert behavior
  • Believing updateOne cannot upsert
5. You want to update the 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?
hard
A. db.users.updateOne({ email: "user@example.com" }, { $set: { status: "active" } }, { upsert: true })
B. db.users.insertOne({ email: "user@example.com", status: "active" })
C. db.users.updateOne({ email: "user@example.com" }, { status: "active" }, { upsert: true })
D. db.users.updateMany({ email: "user@example.com" }, { $set: { status: "active" } })

Solution

  1. Step 1: Identify the correct update syntax with upsert

    To update or insert, use updateOne with a filter, an update using $set, and {upsert: true} option.
  2. Step 2: Check each option

    db.users.updateOne({ email: "user@example.com" }, { $set: { status: "active" } }, { upsert: true }) uses $set and upsert correctly. db.users.insertOne({ email: "user@example.com", status: "active" }) only inserts, no update. db.users.updateOne({ email: "user@example.com" }, { status: "active" }, { upsert: true }) misses $set operator, which replaces the whole document incorrectly. db.users.updateMany({ email: "user@example.com" }, { $set: { status: "active" } }) updates many but no upsert.
  3. Final Answer:

    db.users.updateOne({ email: "user@example.com" }, { $set: { status: "active" } }, { upsert: true }) -> Option A
  4. Quick Check:

    Use updateOne + $set + upsert: true [OK]
Hint: Use $set with upsert: true in updateOne to update or insert [OK]
Common Mistakes:
  • Omitting $set causing document replacement
  • Using insertOne which does not update
  • Forgetting upsert option for insert fallback