$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.

CategoryUpdate Field
MongoDB Version1.0+
Example Languagemongosh (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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏