An application needs to update a user document by incrementing the 'login_count' field by 1 only if the 'status' field is set to 'active'. Which method is most efficient for this atomic operation?
Trap 1: db.users.save({status: 'active', $inc: {login_count: 1}})
The save method is deprecated and treats the document as a full replacement, not an atomic increment. It would overwrite the entire document with the provided object, potentially losing other existing fields or failing to perform the intended mathematical increment operation on the database server side.
Trap 2: db.users.findAndModify({query: {status: 'active'}, update: {$inc:…
While findAndModify works, it is technically an older legacy command. Modern MongoDB drivers and the shell prefer the updateOne method for standard updates. Using findAndModify is usually reserved for scenarios where returning the document state before or after the modification is strictly required by the business logic.
Trap 3: db.users.updateMany({status: 'active'}, {$set: {login_count: 1}})
This operation uses $set instead of $inc, which would force the value to 1 instead of incrementing it. Additionally, updateMany affects all matching documents, which might be dangerous if you only intend to update one specific user document based on a unique identifier like an ID.
- A
db.users.save({status: 'active', $inc: {login_count: 1}})
Why it fails: The save method is deprecated and treats the document as a full replacement, not an atomic increment. It would overwrite the entire document with the provided object, potentially losing other existing fields or failing to perform the intended mathematical increment operation on the database server side.
- B
db.users.findAndModify({query: {status: 'active'}, update: {$inc: {login_count: 1}}})
Why it fails: While findAndModify works, it is technically an older legacy command. Modern MongoDB drivers and the shell prefer the updateOne method for standard updates. Using findAndModify is usually reserved for scenarios where returning the document state before or after the modification is strictly required by the business logic.
- C
db.users.updateOne({status: 'active'}, {$inc: {login_count: 1}})
This is the most efficient and idiomatic approach. The updateOne method accepts a filter to target the specific document and the $inc operator to perform the arithmetic operation atomically. This minimizes server load and ensures that the increment happens correctly even under high concurrency scenarios without requiring application-side locks.
- D
db.users.updateMany({status: 'active'}, {$set: {login_count: 1}})
Why it fails: This operation uses $set instead of $inc, which would force the value to 1 instead of incrementing it. Additionally, updateMany affects all matching documents, which might be dangerous if you only intend to update one specific user document based on a unique identifier like an ID.