0
0
MongoDBquery~5 mins

$set operator for setting fields in MongoDB

Choose your learning style9 modes available
Introduction

The $set operator is used to change or add specific fields in a document without replacing the whole document.

You want to update a user's email address in their profile.
You need to add a new field like 'lastLogin' to existing documents.
You want to correct a typo in a product's description.
You want to change the status of an order from 'pending' to 'shipped'.
Syntax
MongoDB
db.collection.updateOne(
  { <filter> },
  { $set: { <field1>: <value1>, <field2>: <value2>, ... } }
)

The updateOne method updates a single document matching the filter.

The $set operator only changes the specified fields and leaves others untouched.

Examples
Updates the email field for the user with username 'alice'.
MongoDB
db.users.updateOne(
  { username: "alice" },
  { $set: { email: "alice@example.com" } }
)
Sets new price and stock values for the product with ID 123.
MongoDB
db.products.updateOne(
  { productId: 123 },
  { $set: { price: 19.99, stock: 50 } }
)
Changes the status of order 456 to 'shipped'.
MongoDB
db.orders.updateOne(
  { orderId: 456 },
  { $set: { status: "shipped" } }
)
Sample Program

This example first adds an employee named John. Then it updates John's role and active status using $set. Finally, it retrieves John's updated document.

MongoDB
db.employees.insertOne({ name: "John", role: "Developer", active: true })
db.employees.updateOne(
  { name: "John" },
  { $set: { role: "Senior Developer", active: false } }
)
db.employees.find({ name: "John" }).toArray()
OutputSuccess
Important Notes

If the field does not exist, $set will add it to the document.

Using $set prevents overwriting the entire document, which can avoid accidental data loss.

Summary

$set changes or adds specific fields in a document.

It is used with update methods like updateOne or updateMany.

Only the fields inside $set are affected; others stay the same.