$set (Set Field)
Last updated: 2026-10-09
$set (Set Field)
$set assigns (or overwrites) the value of one or more fields in a document. It creates the field if it does not exist and supports dotted paths for nested fields. It is the most commonly used update operator. `{ $set: { "price": 19.99, "inStock": true } }` sets multiple fields at once.
| Category | Update Field |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $set: { <field1>: <value1>, <field2>: <value2>, ... } }
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $set: set multiple fields
db.products.updateOne(
{ _id: 1 },
{ $set: { price: 19.99, inStock: true } }
)
Output:
// Returns updatedCount: 1; document price becomes 19.99 and inStock true
📌 Notes
- Semantics match pre-5.0 $set; array-update semantics changed slightly from MongoDB 7.0
- Use updateMany to apply to all matching documents
- $set overwrites existing fields, it does not merge
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QCan $set and $inc be used together?
AYes. $set assigns a fixed value while $inc performs arithmetic; both can appear in one update (except on the same field).
QHow does $set differ from plain assignment in update?
A$set updates only the named fields and leaves the rest of the document untouched. Replacing the whole document requires replaceOne, which drops any fields not specified.
QDoes $set overwrite existing fields?
AYes. $set overwrites existing fields with the new value and creates missing ones. It is idempotent: repeating the same $set yields the same result.