0
0
MongoDBquery~20 mins

$inc operator for incrementing in MongoDB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
MongoDB $inc Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2: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 })
A{ _id: 1, score: 5 }
B{ _id: 1, score: 15 }
C{ _id: 1, score: 10 }
DError: $inc requires a numeric value
Attempts:
2 left
💡 Hint
Think about what adding 5 to 10 results in.
📝 Syntax
intermediate
2:00remaining
Identify the correct $inc syntax
Which of the following update commands correctly increments the count field by 3 in MongoDB?
Adb.collection.updateOne({}, { $inc: count: 3 })
Bdb.collection.updateOne({}, { inc: { count: 3 } })
Cdb.collection.updateOne({}, { $inc: { count: 3 } })
Ddb.collection.updateOne({}, { $inc: { count += 3 } })
Attempts:
2 left
💡 Hint
Remember the $inc operator must be inside an object with the field name as key.
optimization
advanced
2: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?
Adb.collection.updateOne({ _id: 1 }, { $inc: { likes: 2 } }); db.collection.updateOne({ _id: 1 }, { $inc: { shares: 1 } })
Bdb.collection.updateOne({ _id: 1 }, { $inc: { likes: 1, shares: 2 } })
Cdb.collection.updateOne({ _id: 1 }, { $set: { likes: likes + 2, shares: shares + 1 } })
Ddb.collection.updateOne({ _id: 1 }, { $inc: { likes: 2, shares: 1 } })
Attempts:
2 left
💡 Hint
Try to do both increments in one command.
🧠 Conceptual
advanced
2: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?
AThe <code>views</code> field is created with value 1
BThe <code>views</code> field is created with value 0
CThe document remains unchanged
DThe update fails with an error
Attempts:
2 left
💡 Hint
Think about how $inc treats missing fields.
🔧 Debug
expert
2: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?
AError: The $inc value must be a number
BNo error, score becomes 'five'
CError: Missing $set operator
DError: Invalid query selector
Attempts:
2 left
💡 Hint
Check the type of the value used with $inc.