Bird
Raised Fist0
MongoDBquery~20 mins

Upsert behavior (update or insert) in MongoDB - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Upsert Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the result of this upsert operation?
Consider a MongoDB collection users with documents:

{ _id: 1, name: "Alice", age: 25 }
{ _id: 2, name: "Bob", age: 30 }

What will be the state of the document with _id: 3 after running this update with upsert?

db.users.updateOne({ _id: 3 }, { $set: { name: "Charlie", age: 22 } }, { upsert: true })
MongoDB
db.users.updateOne({ _id: 3 }, { $set: { name: "Charlie", age: 22 } }, { upsert: true })
AThe document with _id: 3 is deleted if it exists; otherwise, a new document is inserted.
BThe document with _id: 3 is updated if it exists; otherwise, no change occurs.
CAn error is thrown because _id: 3 does not exist.
DA new document { _id: 3, name: "Charlie", age: 22 } is inserted.
Attempts:
2 left
💡 Hint
Upsert means update if found, insert if not found.
🧠 Conceptual
intermediate
1:30remaining
Which statement best describes the upsert option in MongoDB?
Choose the most accurate description of what the upsert option does in MongoDB update operations.
AIt updates the first document matching the filter or inserts a new document if none match.
BIt only inserts a new document and never updates existing ones.
CIt updates all documents matching the filter and inserts a new document if none match.
DIt deletes documents matching the filter and inserts a new document.
Attempts:
2 left
💡 Hint
Upsert combines update and insert behavior.
📝 Syntax
advanced
2:00remaining
Which updateOne command correctly performs an upsert to set age to 40 for user with _id 5?
Select the MongoDB command that correctly updates the age to 40 for the document with _id 5, inserting it if it does not exist.
Adb.users.updateOne({ _id: 5 }, { age: 40 }, { upsert: true })
Bdb.users.updateOne({ _id: 5 }, { $set: { age: 40 } }, { upsert: true })
Cdb.users.updateOne({ _id: 5 }, { $set: age: 40 }, { upsert: true })
Ddb.users.updateOne({ _id: 5 }, { $update: { age: 40 } }, { upsert: true })
Attempts:
2 left
💡 Hint
Update operators like $set are required to modify fields.
🔧 Debug
advanced
2:30remaining
Why does this upsert operation fail with a duplicate key error?
Given a collection with a unique index on the field email, what causes this error?

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

Assume a document with email: "user@example.com" already exists.
AThe $set operator cannot be used with upsert.
BThe update document is missing the _id field required for upsert.
CThe upsert tries to insert a new document with duplicate email violating the unique index.
DThe filter matches multiple documents causing a duplicate key error.
Attempts:
2 left
💡 Hint
Unique indexes prevent duplicate values on indexed fields.
optimization
expert
3:00remaining
How to optimize bulk upsert operations in MongoDB for large datasets?
You need to perform thousands of upsert operations efficiently on a MongoDB collection. Which approach is best to optimize performance?
AUse bulkWrite with updateOne operations including upsert:true in a single batch.
BInsert all documents and catch duplicate key errors to update existing ones.
CRun individual updateOne operations with upsert:true in a loop.
DDelete all documents first, then insert all new documents.
Attempts:
2 left
💡 Hint
Batch operations reduce network overhead and improve speed.

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