Open In App

MongoDB – updateOne() Method

The updateOne() method in MongoDB updates the first matched document within the collection based on the given query.

The value of the _id field remains unchanged after updating the value. This method updates one document at a time and can also add new fields to the given document.



Important Points:

MongoDB updateOne() Method Syntax

db.collection.updateOne(<filter>, <update>, {
   upsert: <boolean>,
   writeConcern: <document>,
   collation: <document>,
   arrayFilters: [<filterdocument1>, ...],
   hint: <document|string> // Available starting in MongoDB 4.2.1
})

Parameters:

Optional Parameters:

Return:

This method returns a document that contains the following fields:

MongoDB updateOne Method Examples

In the following examples, we are working with:



Database: gfg

Collection: student

Document: Four documents contains name and age of the students

Update an Integer Value in the Document with the updateOne() Method Example

Update the age of the student whose name is Annu

Query:

db.student.updateOne({name: "Annu"}, {$set:{age:25}})

Output:

Explanation:

Here, the first parameter is the document whose value is to be changed i.e. {name:”Annu”} and the second parameter is the set keyword means to set(update) the following first matched key value with the older key value, i.e., from 20 to 25.

Update a String Value in the Document with the updateOne() Method Example

Update the name of the first matched document whose name is Bhannu to Babita

Query:

db.student.updateOne({name:"Bhannu"},{$set:{name:"Babita"}})

Output:

Explanation:

Here, the first parameter is the document whose value is to be changed {name:”Bhannu”} and the second parameter is the set keyword means to set(update) the following first matched key value with the older key value.

Note: Here, the value of the key must be of the same data type that was defined in the collection.

Insert a new field in the document using the updateOne method Example

Query:

db.student.updateOne({name: "Bhannu"}, {$set:{class: 3}})

Output

Explanation:

Here, a new field is added, i.e., class: 3 in the document of a student whose name is Bhannu.

Article Tags :