$set

Sets the value of fields in documents, creating new fields if they don't exist or updating existing field values.

Syntax

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

Parameters

fieldstringrequired

Field name to create or update

valueobjectrequired

Value to assign to the field

Examples

Update product information

Set multiple fields with new values

Query:

db.products.updateOne({ productId: "prod123" }, { $set: { price: 24.99, status: "active", lastModified: new Date() } })

Output:

Updates price, status, and lastModified fields with specified values

Add new fields to document

Create new fields that don't currently exist

Query:

db.users.updateOne({ userId: "user456" }, { $set: { "profile.bio": "Software developer", "preferences.theme": "dark" } })

Output:

Adds bio to profile and theme to preferences, creating nested structure

Related