How to Use $set Operator in MongoDB: Syntax and Examples
In MongoDB, the
$set operator updates the value of a field in a document or adds the field if it does not exist. It is used inside update commands to modify specific fields without replacing the entire document.Syntax
The $set operator is used within an update command to specify the fields to update and their new values.
- filter: Selects the document(s) to update.
- update: Contains the
$setoperator with field-value pairs to update. - options: Optional settings like
upsertormulti.
mongodb
db.collection.updateOne(
{ <filter> },
{ $set: { <field1>: <value1>, <field2>: <value2>, ... } }
)Example
This example updates the age field of a user document with name 'Alice' to 30. If the age field does not exist, it will be added.
mongodb
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 30 } }
)Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Common Pitfalls
Common mistakes when using $set include:
- Using
$setwithout an update operator, which replaces the whole document instead of updating fields. - Forgetting to specify a filter, which can update multiple or all documents unintentionally.
- Trying to update nested fields without using dot notation.
mongodb
/* Wrong: Replaces entire document */ db.users.updateOne( { name: "Alice" }, { age: 30 } ) /* Right: Uses $set to update only the age field */ db.users.updateOne( { name: "Alice" }, { $set: { age: 30 } } )
Quick Reference
| Usage | Description |
|---|---|
| $set: { field: value } | Updates or adds the specified field with the given value. |
| updateOne(filter, { $set: {...} }) | Updates the first document matching the filter. |
| updateMany(filter, { $set: {...} }) | Updates all documents matching the filter. |
| dot notation | Use dot notation to update nested fields, e.g., $set: { 'address.city': 'NY' } |
Key Takeaways
Use
$set to update or add specific fields without replacing the whole document.Always include a filter to target the correct documents for update.
Use dot notation to update nested fields inside documents.
Without
$set, the update command replaces the entire document.You can update one or many documents using
updateOne or updateMany with $set.