$getField (Get Field by Name)

Last updated: 2026-10-09

$getField (Get Field by Name)

$getField fetches a field by its literal name from a document, without parsing the name as a field path even if it starts with $ or contains special characters. The syntax is { $getField: { field: field-name, input: document } }, with input defaulting to $$CURRENT. It is used for dynamic field names or names with special characters. A missing field returns null. Compared with writing '$field' directly, $getField is more flexible but more verbose.

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

📝 Syntax

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

⚙️ Parameters

fieldThe field name as a string or an expression resolving to a string.
inputOptional target document; defaults to $$CURRENT.

Returns:The field value; null when the field is missing or input is null

▶ Example

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

// $getField: fetch a field by name from the current document
db.orders.aggregate([
  { $project: {
      price: { $getField: { field: 'price', input: '$$CURRENT' } }
  } }
])

Output:

{ '_id': 1, 'price': 199 }
{ '_id': 2, 'price': 59 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow does $getField differ from writing $field directly?
ADirect paths are parsed for dots and $, while $getField looks up the literal name and supports special characters and dynamic names.
QCan $getField fetch names containing dots?
AYes, the name is treated literally and is not split into nested paths.
QWhat happens if I omit the input of $getField?
AIt defaults to $$CURRENT, the current document.
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%

🙏 帮我们做得更好

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

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