$set

The `$set` operator updates an existing field or creates a new field with the specified value if it does not exist. One or more fields listed are updated or created. The dot notation is used to update or create nested objects.

Syntax

{
  $set: {
    newField: <expression>
  }
}

Parameters

newFieldobjectrequired

The name of the field to update or create with the expression that defines the value.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "sales": { "totalSales": 75670 }
}

Update an existing field

Update the name field with a new value.

This query updates the store name to a new value.

Query:

db.stores.updateOne(
  { _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" },
  { $set: { name: "Lakeshore Retail" } }
)

Update a nested field

Update a field within a nested object using dot notation.

This query updates the part-time staff count.

Query:

db.stores.updateOne(
  { _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" },
  { $set: { "staff.totalStaff.partTime": 9 } }
)

Create a new field

Create a new field that doesn't exist.

This query adds a formerName field to the document.

Query:

db.stores.updateOne(
  { _id: "8eefe8bd-5d6f-4038-90e8-05a8277637f0" },
  { $set: { formerName: "Tailwind Traders | Drone Shoppe" } }
)

Related