Consider a MongoDB collection users with a document:
{ "name": "Alice", "age": 25 }We run this update query:
db.users.updateOne({ "name": "Alice" }, { $set: { "age": 26 } })What will be the value of age for Alice after this update?
db.users.updateOne({ "name": "Alice" }, { $set: { "age": 26 } })
db.users.find({ "name": "Alice" }).toArray()Think about what $set does in an update operation.
The $set operator changes the value of the specified field. Here, it updates age from 25 to 26.
Why do we need to update documents in a database like MongoDB?
Think about how data changes over time.
Updating documents allows us to modify existing data efficiently without removing and adding new documents, which keeps data consistent and operations faster.
Given a document { "name": "Bob", "score": 10 }, which MongoDB update query correctly increases score by 5?
Look for the operator that increments numeric fields.
The $inc operator increments the value of a field by the specified amount. Other options are invalid operators or incorrect syntax.
Consider this update query:
db.products.updateOne({ "id": 101 }, { "price": 19.99 })Why will it replace the entire document instead of just updating the price field?
Check the structure of the update document.
When no update operator like $set is used, MongoDB replaces the entire document with the update document. Use $set to update only specific fields.
You want to increase the stock field by 10 for all products with category "books". Which query is the most efficient?
Consider the difference between updateOne and updateMany.
updateMany updates all matching documents in one operation, which is more efficient than looping with updateOne. Option C updates all documents, not just books.