Docs Menu
Docs Home
/
MongoDB Manual
/ / / /

$set

On this page

  • Definition
  • Compatibility
  • Syntax
  • Behavior
  • Examples

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.

You can use $set for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

The $set operator expression has the following form:

{ $set: { <field1>: <value1>, ... } }

To specify a <field> in an embedded document or in an array, use dot notation.

In MongoDB 4.4 and earlier, update operators process document fields in lexicographic 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.

Consider a collection products with the following document:

{
_id: 100,
sku: "abc123",
quantity: 250,
instock: true,
reorder: false,
details: { model: "14Q2", make: "xyz" },
tags: [ "apparel", "clothing" ],
ratings: [ { by: "ijk", rating: 4 } ]
}

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.

db.products.update(
{ _id: 100 },
{ $set:
{
quantity: 500,
details: { model: "14Q3", make: "xyz" },
tags: [ "coats", "outerwear", "clothing" ]
}
}
)

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.

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:

db.products.update(
{ _id: 100 },
{ $set: { "details.make": "zzz" } }
)

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.

db.products.update(
{ _id: 100 },
{ $set:
{
"tags.1": "rain gear",
"ratings.0.rating": 2
}
}
)

For additional update operators for arrays, see Array Update Operators.

Tip

See also:

Back

$rename