...

/

Update Documents: Part 2

Update Documents: Part 2

Learn and practice the operators used in updating documents.

Update document arguments

A MongoDB document update is performed through update operations, which tell the MongoDB what to do with the provided field value. The update document, the document that defines how the original document is updated, can contain more than one operator.

$set operator

The $set operator is used to set or update a field value.

Example:

We run the below command to change the priority of the task.

Press + to interact
db.tasks.updateOne({
name: "Learn MongoDB Topic 1"
},
{
$set: {
priority: 2
}
});

In the above example, we use the name field. Ideally, though, we should replace it with the primary field _id.

We can also use the $set operator to update multiple fields.

Press + to interact
db.tasks.updateOne({
name: "Learn MongoDB Topic 1"
},
{
$set: {
status: "completed",
progress; 10,
priority: 2
}
});

We also use it to update the embedded document value.

Press + to interact
db.tasks.updateOne({
name: "Learn MongoDB Topic 1"
},
{
$set: {
"team.location.address": "USA",
}
});

If the field or path we provide does not exist in the embedded document field, MongoDB creates it.

$unset operator

The ...