$set
On this page
Definition
-
$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
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.
Examples
Consider a collection products
with the following document:
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 replaces the value of: quantity
to 500
; the details
field to a new embedded document, and the tags
field to a 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:
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.
For additional update operators for arrays, see Array Update Operators.