Update Operators

MongoDB Update Operators

Updating data requires specific instructions. Update operators tell MongoDB exactly what to change. Without them, you might overwrite entire documents accidentally.

The $set Operator

The $set operator updates the value of a specific field. It leaves all other fields in the document untouched. It is the safest and most common update method.

The $unset Operator

Sometimes you need to delete a specific field. You do not delete the whole document, just the key. Use $unset to completely remove a property.

The $inc Operator

The $inc operator increments a numeric value. It is perfect for counters, like page views or likes. It is highly efficient and thread-safe.

Array Update Operators

MongoDB handles array manipulation brilliantly. Use $push to add a new item to an array. Use $pull to remove an item from an array.

Update Operator Examples:

// Increment a user's login count by 1
db.users.updateOne(
  { name: "John Doe" },
  { $inc: { loginCount: 1 } }
);

// Add a new tag to the skills array db.users.updateOne( { name: "Jane" }, { $push: { skills: "MongoDB" } } );

The $addToSet Operator

$push allows duplicate items in your arrays. $addToSet ensures the item is added uniquely. It is ideal for maintaining unique tag lists.

The $rename Operator

Sometimes field names change in your schema. The $rename operator modifies the key name itself. The actual data value inside remains exactly the same.

Current Date Operator

Tracking modification times is a best practice. Use $currentDate to set a field to the exact timestamp. It is automatically generated by the database server.

Summary

Update operators are strictly required for safe updates. Use $inc for numbers and $push for arrays. Master these to build highly interactive applications.

Exercise

Which operator safely adds an item to an array only if it doesn't already exist?