How to Update Objects in a Document's Array in MongoDB?
Last Updated :
23 Oct, 2024
In the area of MongoDB, managing a database with a large collection of documents can be challenging especially when it comes to updating specific objects within arrays of nested objects. This scenario is common in NoSQL databases like MongoDB.
In this article, we’ll explore some methods for updating objects within a document's array in MongoDB. Whether a MongoDB beginner or an experienced user by mastering these techniques will enhance our database management skills and simplify our data manipulation processes.
How to Update Objects in a Documents Array (Nested Updating) in MongoDB?
When working with MongoDB, updating objects within an array requires specific handling to ensure that only the intended objects are modified while leaving the rest of the document unchanged.
MongoDB provides several methods to achieve this. Below is the method that helps us to Update Objects in a Document's Array (Nested Updating) in MongoDB.
- Using UpdateOne Method
- Using UpdateMany Method
1. UpdateOne Method
The updateOne() method is utilized to modify a single document that meets the specified filter criteria within a collection. If multiple documents match the filter, only the first document encountered is updated.
Syntax:
db.collection.updateOne(
<filter>,
<update>,
{
arrayFilters: [ { <filterCondition> } ],
multi: true
}
)
Explanation:
- <filter>: This is the criteria to select the documents to update.
- <update>: This is the update operation to perform, including the modifications to the array elements.
- arrayFilters: This option specifies the conditions to identify the array elements to update.
- multi: true: This option ensures that all matching array elements are updated (optional).
Example: Here, We Are Updating The Value Of The HTML Course Duration From 4 Weeks To 5 Weeks Using The updateOne Method.
Suppose we have a gfg database in courses collection which stores information about various courses. Each document in the collection represents a course and contains details such as the course name, Instructor name, fees, and duration.
After inserting a record into the courses collection, Our courses look like:
Sample CollectionQuery:
Let's Update the "duration" field of the "HTML" course in a MongoDB collection to "5 weeks" using the positional operator.
db.collection.update(
{ "_id": 1, "courses.name": "HTML" },
{ "$set": { "courses.$.duration": "5 weeks" } }
)
Output:
using updateOne() MethodExplanation: This query updates the "duration" field of the nested object within the "courses" array where the "name" field is "HTML" and the "_id" of the document is 1. The positional operator $
is used to update the matching element in the "courses" array.
2. UpdateMany Method
The updateMany() method is used to update all documents that match the specified filter criteria in a collection.
Syntax:
db.collection.updateMany(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
hint: <document|string> // Available starting in MongoDB 4.2
arrayFilters: [ ... ]
}
)
Explanation:
- db.collection.updateMany(): This is the method call for the updateMany operation on a specific collection.
- <filter>: This is a document that specifies the selection criteria for the update operation. It identifies the documents to be updated.
- <update>: This is a document that describes the modifications to be made to the selected documents.
- upsert (optional): If set to `true`, the operation creates a new document when no document matches the query criteria. The default value is false.
- writeConcern (optional): A document expressing the write concern.
- collation (optional): Specifies the collation to use for the operation.
Example: Here We Are Adding The Value Of The Fees In Every Course Using The updateMany Method.
Query:
Let's Update the "fees" field of all courses in a MongoDB collection to "2000" using the all positional operator.
db.courses.updateMany(
{},
{ "$set": { "courses.$[].fees": "2000" } }
)
Output:
updateManyExplanation: In the query db.courses.updateMany({}, { "$set": { "courses.$[].fees": "2000" } })
updates the "fees" field of all nested objects within the "courses" array in every document of the "courses" collection to "2000". The positional operator $[]
is used to update all elements of the "courses" array in each document.
Conclusion
Overall, updating objects within a document's array in MongoDB requires careful consideration to ensure that only the intended objects are modified. The `updateOne` method updates a single document that meets the specified filter criteria, whereas the `updateMany` method modifies all documents that fulfill the same criteria.
By using these methods, along with the arrayFilters option, developers can efficiently update nested objects in MongoDB arrays. Understanding these techniques not only improves your MongoDB skills but also optimizes your overall data management strategies in distributed applications.
Similar Reads
How to Update the First Object in an Array in MongoDB
MongoDB, a popular NoSQL database, offers powerful features for handling complex data structures. One common scenario is updating specific elements within arrays stored in documents. In this guide, we'll focus on updating the first object in an array within a MongoDB document. We'll cover the concep
3 min read
How to Update the _id of MongoDB Document?
In MongoDB, the _id field serves as a unique identifier for each document in a collection. While MongoDB automatically generates _id values for documents upon insertion, there are scenarios where we might need to update the _id of a document. In this article, We will learn about How to update the _i
3 min read
How to Update Multiple Array Elements in MongoDB?
MongoDB, the popular NoSQL database, offers powerful features for manipulating data, including the ability to update multiple array elements within a document. Efficiently updating multiple elements in an array can be important in various scenarios, such as managing user preferences, and handling in
3 min read
How to push data in a MongoDB document ?
The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collectio
2 min read
How to Update Deeply Nested Array in MongoDB/ Mongoose ?
In MongoDB/Mongoose, updating deeply nested arrays can be challenging due to the nested structure. This article will explore various approaches to update deeply nested arrays efficiently using both MongoDB queries and Mongoose methods. Explaining each approach one by one below: Table of Content Usin
2 min read
Updating a Property of an Object in an Array within a MongoDB Document
In MongoDB, it's common to store complex data structures within documents, including arrays of objects. Updating the property of an object within such an array can be a frequent requirement in many applications. This article will explore various methods to achieve this task, covering concepts like a
3 min read
How to Get only the Objecte of Document in MongoDB
In MongoDB, the ability to extract specific objects from documents is an important skill that can significantly enhance our data retrieval capabilities. MongoDB's flexible document model allows for nested structures, where documents can contain arrays or sub-documents. However, retrieving only the d
3 min read
How to Retrieve only the Queried Element in an Object Array in MongoDB Collection
In MongoDB, retrieving specific elements from an object array within a document is a common requirement, especially when dealing with complex data structures. MongoDB provides powerful query operators to filter and retrieve only the elements that match certain criteria within an array. This capabili
4 min read
How to update single and multiple documents in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
2 min read
How to Push Item From an Array in Mongoose?
In Mongoose, pushing an item to an array can be done using different approaches. To push an item into an array, you can use the $push operator along with the updateOne() or updateMany() method. We will discuss the different methods to push items from an array in Mongoose: Table of Content Inserting
5 min read