0
0
MongoDBquery~10 mins

Upsert behavior (update or insert) in MongoDB - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to perform an upsert operation in MongoDB.

MongoDB
db.collection.updateOne({ _id: 1 }, { $set: { name: 'Alice' } }, { [1]: true })
Drag options to blanks, or click blank then click option'
Aupdate
Bupsert
Cinsert
Dreplace
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'insert' instead of 'upsert' causes an error because 'insert' is not a valid option here.
Omitting the option means no insert will happen if no document matches.
2fill in blank
medium

Complete the code to update a document or insert it if it does not exist.

MongoDB
db.users.updateOne({ username: 'bob' }, { $set: { age: 30 } }, { [1]: true })
Drag options to blanks, or click blank then click option'
Areplace
Bmulti
Cinsert
Dupsert
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'replace' will replace the whole document but does not insert if missing.
Using 'multi' is invalid for updateOne.
3fill in blank
hard

Fix the error in the upsert operation code.

MongoDB
db.products.updateOne({ sku: '123' }, { $set: { price: 20 } }, { [1]: true })
Drag options to blanks, or click blank then click option'
Aupdate
Binsert
Cupsert
Dmulti
Attempts:
3 left
💡 Hint
Common Mistakes
Setting 'upsert' to a string instead of boolean causes the operation to fail.
Using 'insert' as an option name is invalid.
4fill in blank
hard

Fill both blanks to create an upsert that sets the field and returns the updated document.

MongoDB
db.inventory.updateOne({ item: 'pencil' }, { [1]: { qty: 50 } }, { [2]: true, returnDocument: 'after' })
Drag options to blanks, or click blank then click option'
A$set
Bupsert
C$inc
Dmulti
Attempts:
3 left
💡 Hint
Common Mistakes
Using '$inc' instead of '$set' changes the value by incrementing instead of setting.
Omitting 'upsert' option means no insert will happen.
5fill in blank
hard

Fill all three blanks to perform an upsert that increments a count, sets a status, and enables upsert.

MongoDB
db.stats.updateOne({ user: 'john' }, { [1]: { count: 1 }, [2]: { status: 'active' } }, { [3]: true })
Drag options to blanks, or click blank then click option'
A$inc
B$set
Cupsert
D$unset
Attempts:
3 left
💡 Hint
Common Mistakes
Using '$unset' removes fields instead of updating.
Omitting 'upsert' option disables insert on no match.