- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $addFields (aggregation)
$addFields (aggregation)¶
On this page
Definition¶
-
$addFields
¶ New in version 3.4.
Adds new fields to documents.
$addFields
outputs documents that contain all existing fields from the input documents and newly added fields.The
$addFields
stage is equivalent to a$project
stage that explicitly specifies all existing fields in the input documents and adds the new fields.Note
Starting in version 4.2, MongoDB adds a new aggregation pipeline stage
$set
that is an alias for$addFields
.$addFields
has the following form:Specify the name of each field to add and set its value to an aggregation expression. For more information on expressions, see Expressions.
Important
If the name of the new field is the same as an existing field name (including
_id
),$addFields
overwrites the existing value of that field with the value of the specified expression.
Behavior¶
$addFields
appends new fields to existing documents. You can
include one or more $addFields
stages in an aggregation operation.
To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example.
To add an element to an existing array field with $addFields
, use
with $concatArrays
. See example.
Examples¶
Using Two $addFields
Stages¶
A collection called scores
contains the following documents:
The following operation uses two $addFields
stages to
include three new fields in the output documents:
The operation returns the following documents:
Adding Fields to an Embedded Document¶
Use dot notation to add new fields to embedded documents.
A collection called vehicles
contains the following documents:
The following aggregation operation adds a new field fuel_type
to
the embedded document specs
.
The operation returns the following results:
Overwriting an existing field¶
Specifying an existing field name in an $addFields
operation
causes the original field to be replaced.
A collection called animals
contains the following document:
The following $addFields
operation specifies the cats
field.
The operation returns the following document:
It is possible to replace one field with another. In the following
example the item
field substitutes for the _id
field.
A collection called fruit
contains the following documents:
The following aggregration operation uses $addFields
to replace
the _id
field of each document with the value of the item
field, and replaces the item
field with a static value.
The operation returns the following:
Add Element to an Array¶
Create a sample scores
collection with the following:
You can use $addFields
with a $concatArrays
expression to add an element to an existing array field. For example,
the following operation uses $addFields
to replace the
homework
field with a new array whose elements are the current
homework
array concatenated with another array containing a new
score [ 7 ]
.
The operation returns the following: