MongoDB provides the following methods to update existing documents in a collection:
- db.collection.updateOne()Ā – Modifies a single document in a collection.
- db.collection.updateMany()Ā – Modifies one or more documents in a collection.
db.collection.updateOne()
Use the db.<collection>.updateOne()
method to update a single document in a collection that matches with the specified filter criteria. It updates the first matching document even if multiple documents match with the criteria.
Syntax:
db.collection.updateOne(filter, document, options)
Parameters:
- filter: The selection criteria for the update, same as find() method.
- document: A document or pipeline that contains modifications to apply.
- options: Optional. May contains options for update behavior. It includes upsert, writeConcern, collation, etc.
In the above syntax, db
points to the current database, <collection>
points is an existing collection name.
To demonstrate the update operation, insert the following sample documents in the employees
collection.
Sample DataĀ
db.employees.insertMany([ { _id:1, firstName: "John", lastName: "King", email: "john.king@abc.com", salary: 5000 }, { _id:2, firstName: "Sachin", lastName: "T", email: "sachin.t@abc.com", salary: 8000 }, { _id:3, firstName: "James", lastName: "Bond", email: "jamesb@abc.com", salary: 7500 }, { _id:4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 7000 }, { _id:5, firstName: "Kapil", lastName: "D", email: "kapil.d@abc.com", salary: 4500 }, { _id:6, firstName: "Amitabh", lastName: "B", email: "amitabh.b@abc.com", salary: 7000 } ])
Update a Single Field
The following updates a single field in a single document in employees
collection.
Example: updateOne() Copy
db.employees.updateOne({_id:1}, { $set: {firstName:'Morgan'}})
Output
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
In the above example, the first parameter is the filter criteria specified as a document, {_id:1}
indicates that find a document whose _id
is 1. The second parameter is used to specify fields and values to be modified on the matching document in the {<update-operator>: { field: value, field:value,... }
format. Use the update operator to specify what action to perform. Here we want to set the value of a field, so use $set
operator to specify fields and updated values in {field:updated-value}
format. { $set: {firstName:'Morgan'}}
modifies the firstName
to "Morgan"
to the first document that matches with the specified criteria {_id:1}
.
In the output, matchedCount
indicates the number of documents that matched with the criteria, and modifiedCount
indicates the number of documents updated. The updateOne()
method will always modify a single document.
Now, check whether it has updated a value or not using the findOne()
method shown below.
Check Updated DocumentĀ
db.employees.find({_id:1})
Output
{ _id: 1, firstName: 'Morgan', lastName: 'King', email: 'john.king@abc.com', salary: 5000 }
The updateOne()
method adds the specified field if it does not exist in a matching document. For example, the following will add the location
field.
Example: updateOne()Ā
db.employees.updateOne({firstName:"Steve"}, { $set: {location: "USA"}})
Output
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
Execute the following find()
method to see the updated data.
Check Updated DocumentĀ
db.employees.find({firstName:"Steve"})
Output
{ _id:4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 7000, location:"USA" }
Use the $inc
update operator to increase the value of the field by the specified amount.
Example: $inc OperatorĀ
db.employees.updateOne({firstName:"Steve"}, { $inc: {salary: 500}})
Output
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
Execute the following find()
method to see the updated data.
Check Updated Document Copy
db.employees.find({firstName:"Steve"})
Output
{ _id:4, firstName: "Steve", lastName: "J", email: "steve.j@abc.com", salary: 7500, location:"USA" }
Update Multiple Fields
You can also specify multiple fields to update. The following updates email
and lastName
fields.
Example: Update Multiple FieldsĀ
db.employees.updateOne({_id:2}, { $set: {lastName:"Tendulkar", email:"sachin.tendulkar@abc.com"}})
Output
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
Execute the following find()
method to see the updated data.
Check Updated DocumentĀ
db.employees.find({_id:2})
Output
{ _id:2, firstName: "Sachin", lastName: "Tendulkar", email: "sachin.tendulkar@abc.com", salary: 8000 }
The updateOne()
method updates a single document only, even if it finds multiple documents. For example, the following updates the first document even if it returns multiple documents.
Example: updateOne()Ā
db.employees.updateOne({salary:7000}, { $set: {salary:7500}})
Output
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
In the above example, the employees
collection contains two documents that have salary:7000
field. However, the updateOne()
modified a single document which is the first document from the matching result.
Upsert – Add if not Exist
Specify {upsert:true}
as a third parameter in the UpdateOne()
method. The upsert:true
adds a new document if the matching document does not found.
Example: UpsertĀ
db.employees.updateOne({firstName:"Heer"}, { $set: {lastName:"Patel", salary:2000}})
Output
{ acknowledged: true, insertedId: ObjectId("6172a2e9ce7d5ca09d6ab082"), matchedCount: 0, modifiedCount: 0, upsertedCount: 1 }
In the above example, MongoDB adds a new document with new _id
, because it cannot find a document with the firstName:"Heer"
.
Update Operators
The following table lists the update operators which can be used with the updateOne()
and updateMany()
methods.
Method | Description |
---|---|
$currentDate | Sets the value of a field to current date, either as a Date or a Timestamp. |
$inc | Increments the value of the field by the specified amount. |
$min | Only updates the field if the specified value is less than the existing field value. |
$max | Only updates the field if the specified value is greater than the existing field value. |
$mul | Multiplies the value of the field by the specified amount. |
$rename | Renames a field. |
$set | Sets the value of a field in a document. |
$setOnInsert | Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents. |
$unset | Removes the specified field from a document. |
Visit Update Operators on MongoDB documentation.
[…] db.collection.updateOne()Ā – Modifies a single document in a collection. […]
[…] can use theĀ updateOne()Ā orĀ updateMany()Ā methods to add, update, or remove array elements based on the specified […]