$getField

Returns the value of a specified field from a document, with support for dynamically determined field names using expressions and variables.

Syntax

{ $getField: { field: <field_name>, input: <input_expression> } }

Parameters

fieldstringrequired

The name of the field to retrieve, can be a string or expression

inputobject

The input document expression, defaults to $$ROOT (current document)

Examples

Get field with dynamic name

Retrieve field value where field name is determined by another field

Query:

db.products.aggregate([{ $addFields: { fieldValue: { $getField: { field: "$fieldName", input: "$$ROOT" } } } }])

Output:

Document with additional fieldValue containing the dynamically selected field

Get field from nested document

Extract field value from a nested document object

Query:

db.products.aggregate([{ $addFields: { itemName: { $getField: { field: "name", input: "$item" } } } }])

Output:

Document with itemName field containing the name from the nested item object

Get field using variable

Use variable to specify field name for retrieval

Query:

db.products.aggregate([{ $addFields: { value: { $getField: { field: { $literal: "$price" }, input: "$$ROOT" } } } }])

Output:

Document with value field containing the price field value

Related