Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create double nested array in MongoDB?
To create a double nested array in MongoDB, use insertOne() or insertMany() with documents containing arrays of objects that themselves contain arrays. A double nested array means an array within an array structure.
Syntax
db.collection.insertOne({
"field1": "value1",
"outerArray": [
{
"innerField": "value",
"innerArray": [
{ "nestedField": "value1" },
{ "nestedField": "value2" }
]
}
]
});
Example 1: Student Project Database
Create a collection storing student details with nested project information ?
db.doubleNestedArrayDemo.insertOne({
"StudentId": "1000",
"StudentName": "Larry",
"StudentDetails": [
{
"ProjectName": "Online Banking",
"ProjectDetails": [
{
"TechnologyUsed": "Java"
},
{
"TechnologyUsed": "MySQL in Backend"
}
]
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5c992bd7330fd0aa0d2fe4cc")
}
Example 2: Multiple Documents at Once
db.doubleNestedArrayDemo.insertMany([
{
"StudentId": "1001",
"StudentName": "Robert",
"StudentDetails": [
{
"ProjectName": "Student Web Tracker",
"ProjectDetails": [
{ "TechnologyUsed": "Django Framework" },
{ "TechnologyUsed": "MongoDB in Backend" }
]
}
]
},
{
"StudentId": "1002",
"StudentName": "Alice",
"StudentDetails": [
{
"ProjectName": "E-commerce Platform",
"ProjectDetails": [
{ "TechnologyUsed": "React.js" },
{ "TechnologyUsed": "Node.js" },
{ "TechnologyUsed": "PostgreSQL" }
]
}
]
}
]);
Verify Results
Display all documents to verify the double nested array structure ?
db.doubleNestedArrayDemo.find().pretty();
{
"_id": ObjectId("5c992bd7330fd0aa0d2fe4cc"),
"StudentId": "1000",
"StudentName": "Larry",
"StudentDetails": [
{
"ProjectName": "Online Banking",
"ProjectDetails": [
{
"TechnologyUsed": "Java"
},
{
"TechnologyUsed": "MySQL in Backend"
}
]
}
]
}
{
"_id": ObjectId("5c992cdb330fd0aa0d2fe4cd"),
"StudentId": "1001",
"StudentName": "Robert",
"StudentDetails": [
{
"ProjectName": "Student Web Tracker",
"ProjectDetails": [
{
"TechnologyUsed": "Django Framework"
},
{
"TechnologyUsed": "MongoDB in Backend"
}
]
}
]
}
Conclusion
Double nested arrays in MongoDB are created by embedding arrays within array elements. This structure is ideal for storing hierarchical data like student projects with multiple technologies, product categories with subcategories, or any parent-child-grandchild relationships.
Advertisements
