updateOne()
is a method in the MongoDB that allows you to update a single document in a collection that matches a specified filter. When the filter returns more than one document, only the first one will be updated and nothing will be changed if there are no documents that fit the filter.
Note that updateOne()
method only updates a single document that matches the filter. If a filter returns multiple documents, it update the first document. If you want to update multiple documents that match a filter, you can use the updateMany()
method instead.
In order to explain the updateOne() method in MongoDB, let’s create the sample collection with a few documents.
# Create Collection by inserting some documents
db.student.insertMany([
{
_id: 1,
name: "Jermy",
age: 24,
marks: 500,
email: "[email protected]",
course: ["Python", "MongoDB", "Java"],
points: [10, 9, 3]
},
{
_id: 2,
name: "Niki",
age: 20,
marks: 450,
email: "[email protected]",
course: ["Python", "MongoDB", "Java"],
points: [5, 9, 3]
},
{
_id: 3,
name: "Ian",
age: 24,
marks: 400,
email: "[email protected]",
course: ["Python", "MongoDB", "Java"],
points: [12, 5, 13]
},
{
_id: 4,
name: "Tyler",
age: 23,
marks: 390,
email: "[email protected]",
course: ["Python", "MongoDB", "Java"],
points: [5, 10, 9]
}
]
)
1. Syntax of updateOne()
Following is the syntax of the updateOne() method.
# Syntax
db.collection('myCollection').updateOne(filter, update, options)
1.1 Paramters
- The
filter
parameter indicates the selection criteria for the document to update. - The
update
specifies that the method takes different options that modify the fields in the selected document. options
is an optional object that specifies additional options for the update operation, such asupsert
,writeConcern
,collation
,arrayFilters
,hint
Options possible values
upsert | It takes the default value as false. When it is true, it creates a new document if no documents match the filter criteria, When a document matches the filter, it updates a single document. |
writeConcern | When used it omits the default write concern. The type of this parameter is a document. |
collation | It specifies the use of the collation for operations. Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. |
arrayFilters | It is an array of filter documents that indicates which array elements to modify for an update operation on an array field. The type of this parameter is an array. |
hint | It takes a document or string values that specifies the index to use to support the filter. It takes the index specification document or the index name string. |
1.2 Returns
The updateOne() method returns a document with follwoing details:
matchedCount
– number of documents matchedmodifiedCount
– number of documents modifiedupsertedId
containing the_id
for the upserted document.acknowledged
–true
if the operation ran with write concern,false
if write concern was disabled
2. Using MongoDB updateOne() method to update the document
The updateOne()
method only updates the initial document that satisfies the query filter. The updateOne()
method takes the filter as argument that selects the document to be updated based on the value.
Here, the query filter name
field equal to Jermy
. then, the updateOne()
method takes the $set
operator to set the value of the age
field to 20
for the selected document.
# Updating one document
db.student.updateOne({name: "Jermy"}, {$set:{age:20}})
The following output yielded indicates that one document has been modified and matched.
The following updated document can be read below.
3. Use the updateOne() to update the document with a new field
The updateOne()
method also adds a field that is not found in the matched document. The query below called the updateOne()
method, with the filter as the first argument to modify the document. The filter uses the name
field to match records where Ian
appears in the document.
After that, the $set
operator is assigned as a second argument of the updateOne()
method. Here, the $set
operator inserts New York
as the value for the location
field for the selected document.
Note that location
doesn’t exist in any of the documents in the collection student
. But the updateOne()
method will insert this field with the specified value in the filtered document.
# Updating document with new field
db.student.updateOne({name:"Ian"},{$set:{location:"New york"}})
The following output represents that the document is matched and modified.
Furthermore, we can see the modified and matched document with the new field location
.
4. Use the updateOne() to update the document by increasing the value
The updateOne()
method also accepts the $inc
operator to increment a numeric field by a specified value. In the below example, the given query of the updateOne()
method updates the document one document that matches the specified filter. As the _id
column has a value of 4
, the filter chooses the updated document according to that value.
Furthermore, the updateOne()
method is set with the $inc
operator that increments the value of the marks
field by 400
for the selected document.
# Updating documents by increasing value
db.student.updateOne({_id: 4}, { $inc: {marks: 400}})
The following result shows that the document is updated by incrementing a specified value of the field.
We read the modified document that appears with the increased value of the marks field below.
5. Use the updateOne() to add the new document if it doesn’t exist
Further, the upsert option can be used in the updateOne()
method to insert the new document if one does not already exist that meets the specified filter.
Note that we have specified the upsert
option after the $set
operator, which creates a new document if one does not already exist that match the specified filter. If there is no document in the student
collection that matches the filter, MongoDB will create a new document with the name
, age
, and email
fields set to the given values, respectively.
# Adding new document if it doesn’t exist
db.student.updateOne({name:"stefan"},
{ $set: {age:27, email:"[email protected]"}},
{ upsert: true }
)
The following output retrieved below indicates that the matched document is not found. But that document has been added to the collection.
The new document upserted in the collection student
like this.
If you want to know how to insert a document if it does not exist, you can use the following link.
6. Using the updateOne() method to update the array fields of the document
The arrays can also be modified via the updateOne()
method. The updateOne()
method query modified the value of the first and second elements of the course
array in the document that matches the filter to C++
and C#
, respectively. Here, the course
field is an array, and the notation .
dot indicates each element’s position within the array.
# Updating array fields in document
db.student.updateOne({ _id: 3 },
{ $set: {
"course.0": "C++",
"course.1": "C#"
}
})
The output verifies that the document is matched and updated the array value.
Now, we have retrieved the document updated with the array field values.
7. Conclusion
In conclusion, you have learned the MongoDB updateOne()
method that is used to update one document. The updateOne()
method offers a variety of update operators that can be used to modify a single document in a collection that matches a given filter. It can also be used to insert a document when document not found.
More details about this topic can be found here.
Related Articles
- MongoDB Create User
- Most Useful Basic MongoDB Commands
- Using MongoDB Index Explained
- List Databases in MongoDB
- MongoDB Interview Questions
- Check MongoDB Version
- Node.js Using Express.js with MongoDB
- MongoDB Create Database & Collection
- Using Mongoose Module with MongoDB
- MongoDB Client Tools (Interact with MongoDB)
- Using MongoDB Index Explained
- MongoDB Schema
- MongoDB vs MySQL Differences