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.


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:

  • This method can accept a document that only holds update operator expressions.
  • This method can also accept aggregation pipelines.
  • In this method, if the value of upsert is set to true for the shard collection, then you must include the full shard key in the filter/selection criteria. Or if the value of upsert is not set to true, then you must include an exact match on the _id field.
  • The update operation will fail if this operation changes the size of the document.
  • You can also use this method inside multi-document transactions.

Similar Reads

MongoDB updateOne() Method Syntax

db.collection.updateOne(, , {   upsert: ,   writeConcern: ,   collation: ,   arrayFilters: [, ...],   hint: // Available starting in MongoDB 4.2.1})...

MongoDB updateOne Method Examples

In the following examples, we are working with:...

Contact Us