Challenge - 5 Problems
MongoDB $inc Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Increment a field using $inc
Given a MongoDB document
{ _id: 1, score: 10 }, what will be the document after applying { $inc: { score: 5 } } update?MongoDB
db.collection.updateOne({ _id: 1 }, { $inc: { score: 5 } })
db.collection.findOne({ _id: 1 })Attempts:
2 left
💡 Hint
Think about what adding 5 to 10 results in.
✗ Incorrect
The $inc operator adds the specified value to the existing field value. Here, 10 + 5 = 15.
📝 Syntax
intermediate2:00remaining
Identify the correct $inc syntax
Which of the following update commands correctly increments the
count field by 3 in MongoDB?Attempts:
2 left
💡 Hint
Remember the $inc operator must be inside an object with the field name as key.
✗ Incorrect
Option C uses the correct MongoDB update syntax with $inc operator and a proper object for the field increment.
❓ optimization
advanced2:00remaining
Efficiently increment multiple fields
You want to increment
likes by 2 and shares by 1 in a single update. Which update command is the most efficient?Attempts:
2 left
💡 Hint
Try to do both increments in one command.
✗ Incorrect
Option D increments both fields in a single atomic update, which is efficient and safe.
🧠 Conceptual
advanced2:00remaining
Behavior of $inc on non-existing fields
What happens when you use
{ $inc: { views: 1 } } on a document that does not have the views field?Attempts:
2 left
💡 Hint
Think about how $inc treats missing fields.
✗ Incorrect
MongoDB creates the field and sets it to the increment value if it does not exist.
🔧 Debug
expert2:00remaining
Diagnose the error in $inc usage
A developer runs this update:
db.collection.updateOne({ _id: 1 }, { $inc: { score: 'five' } }). What error will MongoDB raise?Attempts:
2 left
💡 Hint
Check the type of the value used with $inc.
✗ Incorrect
The $inc operator requires a numeric value; using a string causes an error.