- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $set (aggregation)
$set (aggregation)¶
On this page
Definition¶
Note
Disambiguation
The following page refers to the aggregation stage
$set, available starting in MongoDB 4.2 For the
update operator $set, see $set.
-
$set¶ New in version 4.2.
Adds new fields to documents.
$setoutputs documents that contain all existing fields from the input documents and newly added fields.The
$setstage is an alias for$addFields.Both stages are equivalent to a
$projectstage that explicitly specifies all existing fields in the input documents and adds the new fields.$sethas 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),$setoverwrites the existing value of that field with the value of the specified expression.
Behavior¶
$set appends new fields to existing documents. You can
include one or more $set 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 $set, use
with $concatArrays. See example.
Examples¶
Using Two $set Stages¶
Create a sample scores collection with the following:
The following operation uses two $set 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.
Create a sample collection vehicles with the following:
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 a $set operation
causes the original field to be replaced.
Create a sample collection called animals with the following:
The following $set operation overrides 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.
Create a sample collection called fruits contains the following
documents:
The following aggregration operation uses $set to replace the
_id field of each document with the value of the item field,
and replaces the item field with a string "fruit".
The operation returns the following:
Add Element to an Array¶
Create a sample scores collection with the following:
You can use $set with a $concatArrays
expression to add an element to an existing array field. For example,
the following operation uses $set 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: