MongoDB Update Operators
Update operators such as $set, $inc, $push, and $unset are the building blocks of every updateOne and updateMany call, each describing one precise kind of change to a document.
$set: Assigning Field Values
$set is the most common update operator: it assigns a new value to one or more fields, creating the field if it doesn't already exist. It never touches any field you didn't name, which makes it safe to use even on documents with many fields you don't want to disturb.
Assign values to one or more fields
db.users.updateOne(
{ _id: 'u-17' },
{ $set: { status: 'verified', verifiedAt: new Date() } }
)$inc: Incrementing Numeric Fields
$inc adds (or subtracts, using a negative number) a numeric amount to a field's current value, in a single atomic step on the server. This matters for counters — like a page view count or an item's stock quantity — where two updates happening at nearly the same time must not overwrite each other's work the way a read-modify-write done in application code would.
Atomically increment and decrement counters
// Add one view
db.articles.updateOne(
{ slug: 'intro-to-mongo' },
{ $inc: { views: 1 } }
)
// Decrease stock by 3
db.products.updateOne(
{ sku: 'ABC-123' },
{ $inc: { stock: -3 } }
)$push: Adding to Arrays
$push appends a value to an array field. Paired with the $each modifier, it can append several values in one call, and combined with $slice or $sort it can also cap an array's length or keep it ordered. Without $each, $push adds exactly the single value given, even if that value is itself an array.
Append one or multiple array entries
// Append a single tag
db.posts.updateOne(
{ _id: 'p-9' },
{ $push: { tags: 'mongodb' } }
)
// Append several tags at once
db.posts.updateOne(
{ _id: 'p-9' },
{ $push: { tags: { $each: ['database', 'nosql'] } } }
)$unset: Removing Fields Entirely
$unset removes a field from a document completely, as opposed to $set: null which would keep the field present with a null value. The value you assign to a field in $unset is ignored by convention (commonly written as an empty string); only the field name matters.
Remove a field from a document
db.users.updateOne(
{ _id: 'u-17' },
{ $unset: { temporaryToken: '' } }
)- $set — assign or overwrite a field's value
- $inc — atomically add to (or subtract from) a numeric field
- $push — append one or more values to an array field
- $unset — remove a field from the document entirely
Exercise: MongoDB Update Operators
What does $unset do to a field during an update?