$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.
| Category | Literal, Variable & Object |
|---|---|
| MongoDB Version | 5.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $getField: { field: <field-name>, input: <document-expression> } }
⚙️ Parameters
| field | The field name as a string or an expression resolving to a string. |
|---|---|
| input | Optional 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
- A field name starting with $ is taken literally, not as a path
- input defaults to $$CURRENT
- A missing field returns null; pair with $ifNull when needed
🏷️ Related Tags
💡 Related Cases
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.