- Reference >
- Operators >
- Update Operators >
- Field Update Operators >
- $set
$set¶
On this page
Definition¶
Note
Disambiguation
The following page refers to the update operator $set
.
For the aggregation stage $set
, available starting in
MongoDB 4.2, see $set
.
-
$set
¶ The
$set
operator replaces the value of a field with the specified value.The
$set
operator expression has the following form:To specify a
<field>
in an embedded document or in an array, use dot notation.
Behavior¶
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.
If the field does not exist, $set
will add a new field with the
specified value, provided that the new field does not violate a type
constraint.
If you specify a dotted path for a non-existent field,
$set
will create the embedded documents as needed to
fulfill the dotted path to the field.
If you specify multiple field-value pairs, $set
will update
or create each field.
Starting in MongoDB 5.0, mongod
no longer raises an
error when you use an update operator like $set
with an empty operand expression ( { }
). An empty update results
in no changes and no oplog entry is created (meaning that the
operation is a no-op).
Examples¶
Create the products
collection:
Set Top-Level Fields¶
For the document matching the criteria _id
equal to 100
, the
following operation uses the $set
operator to update the
value of the quantity
field, details
field, and the tags
field.
The operation updates the:
- value of
quantity
to500
details
field with new embedded documenttags
field with new array
Set Fields in Embedded Documents¶
To specify a <field>
in an embedded document or in an array, use
dot notation.
For the document matching the criteria _id
equal to 100
, the
following operation updates the make
field in the details
document:
After updating, the document has the following values:
Set Elements in Arrays¶
To specify a <field>
in an embedded document or in an array, use
dot notation.
For the document matching the criteria _id
equal to 100
, the
following operation updates the value second element (array index of
1
) in the tags
field and the rating
field in the first
element (array index of 0
) of the ratings
array.
After updating, the document has the following values:
For additional update operators for arrays, see Array Update Operators.