Problem Statement
Which operator is used to update or add a field in a MongoDB document?
Explanation
The dollar set operator is used to update the value of a field or add a new field if it does not exist. This is the most common update operator in MongoDB.
If the field already exists, dollar set updates its value. If the field does not exist, dollar set adds the field with the specified value. This makes it safe to use for both updating existing fields and adding new ones without worrying about whether the field exists.
Code Solution
SolutionRead Only
// Update existing field
db.users.updateOne(
{ name: "John" },
{ $set: { age: 31 } }
)
// Add new field
db.users.updateOne(
{ name: "John" },
{ $set: { email: "john@example.com" } }
)