MongoDB – Update() Method
MongoDB update operations allow us to modify documents in a collection. These operations can update a single document or multiple documents based on specified criteria.
MongoDB offers various update operators to perform specific actions like setting a value, incrementing a value or updating elements within arrays. In this article, We will learn about MongoDB update() by understanding various examples in detail.
MongoDB update()
The MongoDB update() method is a method that is used to update a single document or multiple documents in the collection. When the document is updated the _id field remains unchanged.
The db.collection.update() method updates a single document by default. To update all documents that match the given query, use the multi: true option. Include the option “multi: true“.
Note: In MongoDB, the update() method has been deprecated in favor of using updateOne() or updateMany() depending on your specific use case.
Syntax
db.COLLECTION_NAME.update({SELECTION_CRITERIA}, {$set:{UPDATED_DATA}}, {
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
})
Explanation: This MongoDB update operation updates documents that match the selection criteria with the specified updated data. Here’s an explanation of the parameters used:
COLLECTION_NAME: The name of the collection to update.SELECTION_CRITERIA: The criteria to select which documents to update.UPDATED_DATA: The new data to set for the selected documents.upsert: (Optional) If set to true, creates a new document when no document matches the selection criteria.multi: (Optional) If set to true, updates multiple documents that match the selection criteria. Default is false, which updates only the first matching document.writeConcern: (Optional) Specifies the level of write concern for the operation.collation: (Optional) Specifies the collation for string comparisons.arrayFilters: (Optional) Filters to determine which elements to modify in an array field.hint: (Optional) Forces MongoDB to use a specific index for the operation.
Examples of MongoDB update
Let set up an environment:
To understand MongoDB update we need a collection called students on which we will perform various operations and queries.
[
{ _id: 1, name: "Alice", age: 25, grades: [
{ grade: "Maths", score: 80 },
{ grade: "Science", score: 85 }
]
},
{ _id: 2, name: "Bob", age: 30, grades: [
{ grade: "Maths", score: 75 },
{ grade: "Science", score: 90 }
]
},
{ _id: 3, name: "Charlie", age: 35, grades: [
{ grade: "Maths", score: 95 },
{ grade: "Science", score: 88 }
]
}
]
Example 1: Update a Single Document
Write a query to update the age of a student named Alice to 26 in the “students” collection.
db.students.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)
Output:
[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 30,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 35,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]
Example 2: Use Update Operator Expressions ($inc and $set)
Write a query to increment the age of a student named Bob by 1 in the “students” collection.
db.students.updateOne(
{ name: "Bob" },
{ $inc: { age: 1 } }
)
Output:
[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 35,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]
Example 3: Insert a New Document if No Match Exists (Upsert)
Write a query to update the age of a student named Charlie to 30 in the “students” collection. If Charlie does not exist, a new document should be inserted with the specified age.
db.students.updateOne(
{ name: "Charlie" },
{ $set: { age: 30 } },
{ upsert: true }
)
Output:
[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]
Example 4: Upsert with Duplicate Values
Write a query to update the age of a student named Alice to 26 in the “students” collection. If Alice does not exist, a new document should be inserted with the specified age.
db.students.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } },
{ upsert: true }
)
Output:
[
{
_id: 1,
name: 'Alice',
age: 26,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]
Example 5: Update with Aggregation Pipeline
Write a query to update the age of a student named Alice by incrementing it by 1 in the “students” collection using an aggregation pipeline in the update operation.
db.students.updateOne(
{ name: "Alice" },
[
{ $set: { age: { $add: ["$age", 1] } } }
]
)
Output:
[
{
_id: 1,
name: 'Alice',
age: 27,
grades: [ { grade: 'Maths', score: 80 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]
Example 6: Update Elements Match arrayFilters Criteria
Write a query to update the score of a student’s “Maths” grade to 85 using an array filter in the “students” collection
db.students.updateOne(
{ _id: 1 },
{ $set: { "grades.$[elem].score": 85 } },
{ arrayFilters: [ { "elem.grade": { $eq: "Maths" } } ] }
)
Output:
[
{
_id: 1,
name: 'Alice',
age: 27,
grades: [ { grade: 'Maths', score: 85 }, { grade: 'Science', score: 85 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]
Example 7: Update Specific Elements of an Array of Documents
Write a query to update the score of a student’s “Science” grade to 90 using an array filter in the “students” collection
db.students.updateOne(
{ _id: 1 },
{ $set: { "grades.$[elem].score": 90 } },
{ arrayFilters: [ { "elem.grade": { $eq: "Science" } } ] }
)
Output:
[
{
_id: 1,
name: 'Alice',
age: 27,
grades: [ { grade: 'Maths', score: 85 }, { grade: 'Science', score: 90 } ]
},
{
_id: 2,
name: 'Bob',
age: 31,
grades: [ { grade: 'Maths', score: 75 }, { grade: 'Science', score: 90 } ]
},
{
_id: 3,
name: 'Charlie',
age: 30,
grades: [ { grade: 'Maths', score: 95 }, { grade: 'Science', score: 88 } ]
}
]
Conclusion
Overall, MongoDB update operations provide a powerful way to modify documents in a collection. Whether you need to update a single document, multiple documents, or perform complex updates using aggregation pipelines, MongoDB’s update capabilities offer flexibility and efficiency. By mastering these update operations, you can efficiently manage your MongoDB data and tailor it to meet your application’s needs
FAQs on MongoDB update()
What is the difference between updateOne() and updateMany() in MongoDB?
The
updateOne()method updates a single document that matches the selection criteria, whileupdateMany()updates all documents that match the criteria.
Can I use the update() method in MongoDB?
The
update()method has been deprecated in favor ofupdateOne()andupdateMany(). It’s recommended to use these newer methods for more specific and clear update operations.
What happens if no documents match the selection criteria and upsert is set to true?
If no documents match the selection criteria and
upsertis set to true, a new document will be created using the selection criteria and the update data provided

