- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $getField (aggregation)
$getField (aggregation)¶
On this page
Definition¶
-
$getField
¶ New in version 5.0.
Returns the value of a specified field from a document. If you don’t specify an object,
$getField
returns the value of the field from$$CURRENT
.You can use
$getField
to retrieve the value of fields with names that contain periods (.
) or start with dollar signs ($
).Tip
Use
$setField
to add or update fields with names that contain dollar signs ($
) or periods (.
).
Syntax¶
$getField
has the following syntax:
Field | Type | Description |
---|---|---|
field |
String | Field in the If |
input |
Object | Default: A valid expression that
contains the |
$getField
has the following shorthand syntax for
retrieving field values from $$CURRENT
:
For this syntax, the argument is equivalent to the value of field
described above.
Behavior¶
- If
field
resolves to anything other than a string constant,$getField
returns an error. - If the
field
that you specify is not present in theinput
object, or in$$CURRENT
if you don’t specify aninput
object,$getField
returnsmissing
. - If
input
evaluates tomissing
,undefined
, ornull
,$getField
returnsnull
. - If
input
evaluates to anything other than an object,missing
,undefined
, ornull
,$getField
returns an error. $getField
doesn’t implicitly traverse objects or arrays. For example,$getField
evaluates afield
value ofa.b.c
as a top-level fielda.b.c
instead of a nested field{ a: { b: { c: } } }
.
See also
Examples¶
Query Fields that Contain Periods (.
)¶
Consider an inventory
collection with the following documents:
The following operation uses the $getField
and
$gt
operators to find which products have a price.usd
greater than 200
:
The operation returns the following results:
Query Fields that Start with a Dollar Sign ($
)¶
Consider an inventory
collection with the following documents:
The following operation uses the $getField
,
$gt
, and $literal
operators to find which
products have a $price
greater than 200
:
The operation returns the following results:
Query a Field in a Sub-document¶
Create an inventory
collection with the following documents:
The following operation returns documents where the number of
$small
items is less than or equal to 20
.
Use these operators to query the collection:
- The
$lte
operator finds values less than or equal to 20. $getField
requires explicitfield
andinput
parameters because the$small
field is part of a sub-document.$getField
uses$literal
to evaluate “$small
”, because the field name has a dollar sign ($
) in it.
Example output: