$setField (Set Field by Name)

Last updated: 2026-10-09

$setField (Set Field by Name)

$setField adds or updates a named field in a document and returns a new document without mutating the input. The syntax is { $setField: { field: field-name, input: document, value: expression } }, and field accepts a dynamic expression. A null value removes the field. It is used when field names contain special characters or must be computed dynamically. A null or missing input returns null. Unlike the $set stage, $setField works inside nested expressions and supports dynamic field names.

CategoryLiteral, Variable & Object
MongoDB Version5.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $setField: { field: <field-name>, input: <document-expression>, value: <expression> } }

⚙️ Parameters

fieldThe field name as a string or an expression resolving to a string.
inputTarget document; a null or missing input yields null.
valueThe value to set; null removes the field.

Returns:A new document with the field set; null when input is null or missing

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $setField: add a tax rate field to each order
db.orders.aggregate([
  { $project: {
      doc: { $setField: { field: 'taxRate', input: '$$CURRENT', value: 0.08 } }
  } }
])

Output:

{ '_id': 1, 'doc': { '_id': 1, 'price': 100, 'taxRate': 0.08 } }
{ '_id': 2, 'doc': { '_id': 2, 'price': 50, 'taxRate': 0.08 } }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QDoes $setField modify the original document?
ANo — documents are immutable in pipelines; $setField returns a new document.
QHow do I remove a field with $setField?
ASet value to null and the field is removed.
QHow do $setField and the $set stage differ?
A$set only handles static field names, while $setField supports dynamic names and nested expressions.
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%

🙏 帮我们做得更好

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

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