The $set operator replaces the value of a field to the specified value. If the field does not exist, the $set operator will add the field with the specified value.

The $set operator expression has the following form:

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

To access fields in embedded documents, use the dot notation.


By default, db.collection.update() method updates the first document that matches the update condition. Use the multi option to update all matching documents.

Update a Single Document

Consider a collection products with the following document:

{ _id: 100, sku: "abc123", quantity: 250, instock: false, details: { model: "14Q2", make: "xyz" } }

The following operation uses the $set operator to update the value of the quantity field to 500, instock field to true, and make field in the details document to "ZYX" for the first document where the field sku has the value "abc123":

    { sku: "abc123" },
    { $set: { quantity: 500, instock: true, "details.make": "ZYX" } }

Update Multiple Documents

To update all matching documents in the collection, specify multi: true option in the update() method, as in the following example which sets the value of the field instock to true for all documents in the products collection where the quantity field is greater than (i.e. $gt) 0 :

   { quantity: { $gt: 0 } },
   { $set: { instock: true } },
   { multi: true }

For more examples, see update().

←   $setOnInsert $unset  →