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
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
ACID Properties in DBMS In the world of DBMS, transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliability. This is where the ACID prop
8 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read