mongo-db
  1. mongo-db-update-operator

Update Operator - ( Querying and Projection )

MongoDB provides several update operators to modify and update documents in a collection. In this page, we will discuss the update operator in MongoDB, which is used to modify fields in a document.

Syntax

The general syntax of the update operator in MongoDB is as follows:

db.collection.updateOne(filter, update, options)

Here, db.collection refers to the MongoDB collection that you want to update. filter is a document that specifies the selection criteria for the update. update contains the modification or update to perform on the selected documents. options is an optional parameter that specifies additional update options.

Example

Let's consider an example where we need to update a document in the employees collection.

{
   _id: ObjectId("5f234b3f4400d2b2d01df6cc"),
   name: "John Doe",
   age: 35,
   salary: 50000
}

Now, we can use the $set operator in MongoDB to update the salary field of the above document.

db.employees.updateOne(
  { name: "John Doe" },
  { $set: { salary: 60000 } }
)

This will update the salary field of the document to 60000.

Output

When the above code is executed, it will update the specified document in the employees collection.

{
   _id: ObjectId("5f234b3f4400d2b2d01df6cc"),
   name: "John Doe",
   age: 35,
   salary: 60000
}

Explanation

The update operator $set is used to set or update the value of a field in a MongoDB document. It takes a document as its value, where the key represents the field to be updated and the value represents the new value to be set.

In the above example, we have used the $set operator to update the salary field for the document with the name "John Doe". The filter parameter is used to identify the document to be updated. In this case, we have filtered based on the name field of the document.

Use

The update operator is used to modify or update documents in a MongoDB collection. It is useful when you need to make changes to the existing documents in the collection, without deleting and recreating the documents.

Important Points

  • The update operator in MongoDB is used to modify and update documents in a collection.
  • The $set operator is used to set or update the value of a field in a MongoDB document.
  • The filter parameter is used to identify the documents to be updated.

Summary

In this page, we discussed the syntax, example, output, explanation, use, and important points of the update operator in MongoDB. The update operator is used to modify or update the fields in a MongoDB document. It is a useful tool for making changes to the existing documents in the collection.

Published on: