db.inventory.updateOne({ _id: 1 }, { $inc: { quantity: 5 } })Assume the document exists.
The $inc operator increases the value of the specified field by the given amount. Since the original quantity is 10, adding 5 results in 15.
{ _id: 1, profile: { name: "Alice", age: 30 } }What will be the document after running:
db.users.updateOne({ _id: 1 }, { $set: { "profile.age": 31 } })The $set operator with dot notation updates only the specified nested field without removing other fields. So profile.age changes to 31, but profile.name remains.
status with value active?db.users.updateOne({ _id: 2 }, { $set: { status: 'active' } })Option A is missing braces around the $set value object, causing a syntax error. The correct syntax requires { $set: { field: value } }.
tags array in documents where it does not already exist. Which update operator is best to avoid duplicates?The $addToSet operator adds a value to an array only if it does not already exist, preventing duplicates. $push always adds the value, possibly creating duplicates.
$inc instead of reading a value, modifying it in application code, and then writing it back?Atomic updates ensure that the update operation is done fully or not at all, preventing conflicts and race conditions when multiple users update the same data concurrently.