Updating data requires specific instructions. Update operators tell MongoDB exactly what to change. Without them, you might overwrite entire documents accidentally.
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.
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 increments a numeric value. It is perfect for counters, like page views or likes. It is highly efficient and thread-safe.
MongoDB handles array manipulation brilliantly. Use $push to add a new item to an array. Use $pull to remove an item from an array.
// 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" } }
);
$push allows duplicate items in your arrays. $addToSet ensures the item is added uniquely. It is ideal for maintaining unique tag lists.
Sometimes field names change in your schema. The $rename operator modifies the key name itself. The actual data value inside remains exactly the same.
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.
Update operators are strictly required for safe updates. Use $inc for numbers and $push for arrays. Master these to build highly interactive applications.
Which operator safely adds an item to an array only if it doesn't already exist?