$set

Definition

  • $set
  • The $set operator replaces the value of a field with thespecified value.

The $set operator expression has the following form:

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

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

Behavior

If the field does not exist, $set will add a new field with thespecified value, provided that the new field does not violate a typeconstraint.If you specify a dotted path for a non-existent field,$set will create the embedded documents as needed tofulfill the dotted path to the field.

If you specify multiple field-value pairs, $set will updateor create each field.

Examples

Consider a collection products with the following document:

  1. {
  2. _id: 100,
  3. sku: "abc123",
  4. quantity: 250,
  5. instock: true,
  6. reorder: false,
  7. details: { model: "14Q2", make: "xyz" },
  8. tags: [ "apparel", "clothing" ],
  9. ratings: [ { by: "ijk", rating: 4 } ]
  10. }

Set Top-Level Fields

For the document matching the criteria _id equal to 100, thefollowing operation uses the $set operator to update thevalue of the quantity field, details field, and the tagsfield.

  1. db.products.update(
  2. { _id: 100 },
  3. { $set:
  4. {
  5. quantity: 500,
  6. details: { model: "14Q3", make: "xyz" },
  7. tags: [ "coats", "outerwear", "clothing" ]
  8. }
  9. }
  10. )

The operation replaces the value of: quantity to 500; thedetails field to a new embedded document, and the tags field toa new array.

Set Fields in Embedded Documents

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

For the document matching the criteria _id equal to 100, thefollowing operation updates the make field in the detailsdocument:

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

Set Elements in Arrays

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

For the document matching the criteria _id equal to 100, thefollowing operation updates the value second element (array index of1) in the tags field and the rating field in the firstelement (array index of 0) of the ratings array.

  1. db.products.update(
  2. { _id: 100 },
  3. { $set:
  4. {
  5. "tags.1": "rain gear",
  6. "ratings.0.rating": 2
  7. }
  8. }
  9. )

For additional update operators for arrays, seeArray Update Operators.

See also

db.collection.update(),db.collection.findAndModify()