How to Update Deeply Nested Array in MongoDB/ Mongoose ?
Last Updated :
16 May, 2024
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:
Using MongoDB's Update Operators
This approach utilizes MongoDB's update operators along with arrayFilters to specify the conditions for updating deeply nested arrays.
db.collection.update(
{ <query> },
{ $set: { "nestedArray.$[outer].innerArray.$[inner].field": value } },
{ arrayFilters: [{ "outer._id": <outerId> }, { "inner._id": <innerId> }] }
);
Using Mongoose's findByIdAndUpdate Method with $ positional operator
In this approach, we use Mongoose's findByIdAndUpdate method along with the $ positional operator to update the deeply nested arrays.
Model.findByIdAndUpdate(
parentId,
{ $set: { "nestedArray.$[outer].innerArray.$[inner].field": value } },
{ arrayFilters: [{ "outer._id": outerId }, { "inner._id": innerId }], new: true }
);
Using Mongoose's findOneAndUpdate Method with arrayFilters
Similar to Approach 2, this approach uses Mongoose's findOneAndUpdate method with arrayFilters to update deeply nested arrays.
Model.findOneAndUpdate(
{ _id: parentId },
{ $set: { "nestedArray.$[outer].innerArray.$[inner].field": value } },
{ arrayFilters: [{ "outer._id": outerId }, { "inner._id": innerId }], new: true }
);
Steps to Create Application (Install Required Modules):
- Install MongoDB and Mongoose.
- Set up a Node.js project with npm init.
- Install required packages:
npm install mongoose
package.json:
"dependencies": {
"mongoose": "^6.1.4"
}
Example: Below is the basic code example:
Node
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
const ChildSchema = new mongoose.Schema({
name: String,
value: Number
});
const ParentSchema = new mongoose.Schema({
nestedArray: [{
outerName: String,
innerArray: [ChildSchema]
}]
});
const ParentModel = mongoose.model('Parent', ParentSchema);
async function updateNestedArray(parentId, outerId, innerId, newValue) {
try {
const updatedParent = await ParentModel.findOneAndUpdate(
{ _id: parentId },
{ $set: { "nestedArray.$[outer].innerArray.$[inner].value": newValue } },
{
arrayFilters: [{ "outer._id": outerId }, { "inner._id": innerId }],
new: true
}
);
console.log("Updated Parent:", updatedParent);
} catch (error) {
console.error("Error updating nested array:", error);
}
}
const parentId = "60a3c08462f7f2085c0a1f6b";
const outerId = "60a3c08462f7f2085c0a1f6c";
const innerId = "60a3c08462f7f2085c0a1f6d";
const newValue = 100;
updateNestedArray(parentId, outerId, innerId, newValue);
Output:
Updated Parent: {
_id: ObjectId("60a3c08462f7f2085c0a1f6b"),
nestedArray: [
{
outerName: "Outer Object",
_id: ObjectId("60a3c08462f7f2085c0a1f6c"),
innerArray: [
{
name: "Inner Object",
_id: ObjectId("60a3c08462f7f2085c0a1f6d"),
value: 100 // Updated value
}
]
}
]
}
Similar Reads
How to Update Objects in a Document's Array in MongoDB? 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
5 min read
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 Filter Array in Subdocument with MongoDB? In MongoDB, working with arrays within subdocuments is a common requirement in many applications. Filtering and manipulating arrays efficiently can significantly enhance the flexibility and enhance our queries. In this article, we'll explore how to filter arrays within subdocuments in MongoDB by cov
5 min read
How to Use $set and $unset Operators in MongoDB MongoDB is a NoSQL database that stores data in documents instead of traditional rows and columns found in relational databases. These documents, grouped into collections, allow for flexible data storage and retrieval. One of MongoDBâs key advantages is its ability to dynamically update documents us
6 min read
How to Push Item From an Array in Mongoose? Mongoose, an Object Data Modeling (ODM) library for Node.js and MongoDB, makes database interactions easier through a comprehensive API. One of the most frequent operations that developers execute using Mongoose is adding an item to an array of a document. In this article, we will discuss the differ
6 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 Updating a Single Subelement in an Array Referenced by Index in MongoDB In MongoDB, arrays are a powerful feature for storing multiple values within a single document. However, updating a specific element within an array, especially by its index can be challenging without a clear understanding of MongoDB's update operations. In this article, we'll explore how to update
4 min read
How to update record without objectID in mongoose? Mongoose is an ODM(Object Data Library) for MongoDB in Node JS that helps to write schema, validation and business logic in a simple way without the hassle of native MongoDB boilerplate. PrerequisitesUnderstanding of Mongoose and MongoDBData Modeling and Schema DesignMongoose Query MethodsApproach t
3 min read
How to Pull Item from an Array in Mongoose ? In Mongoose, pulling an item from an array can be done using several methods. To pull an item from an array, you can use the $pull operator along with the updateOne() or updateMany() method. We will discuss the different methods to pull items from an array in Mongoose Table of Content Using $pull Op
5 min read