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
Selected Reading
Creating hierarchical JSON in MongoDB?
To create hierarchical JSON in MongoDB, structure your documents using nested objects and arrays. MongoDB natively supports complex JSON structures with multiple levels of nesting, allowing you to model relationships within a single document.
Syntax
db.collection.insertOne({
"field1": "value1",
"field2": "value2",
"nestedObject": {
"subField1": "value",
"subField2": "value",
"nestedArray": [
{
"arrayField1": "value",
"arrayField2": "value"
}
]
}
});
Example
Let us create a document with hierarchical structure ?
db.demo716.insertOne({
"id": 101,
"UserEmailId": "John@gmail.com",
"UserPassword": "123456",
"UserInformation": {
"UserName": "Chris",
"UserAge": 26,
"UserCountryName": "US",
"OtherInformation": [
{
"TeacherName": "Robert",
"SubjectName": "MongoDB",
"CollegeName": "MIT"
}
]
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5ea9b1ff85324c2c98cc4c2f")
}
Display the Document
Use the find() method to display the hierarchical document ?
db.demo716.find().pretty();
{
"_id": ObjectId("5ea9b1ff85324c2c98cc4c2f"),
"id": 101,
"UserEmailId": "John@gmail.com",
"UserPassword": "123456",
"UserInformation": {
"UserName": "Chris",
"UserAge": 26,
"UserCountryName": "US",
"OtherInformation": [
{
"TeacherName": "Robert",
"SubjectName": "MongoDB",
"CollegeName": "MIT"
}
]
}
}
Key Points
-
Nested objects use curly braces
{}to group related fields -
Arrays use square brackets
[]to store multiple documents - Multiple levels of nesting are supported for complex data modeling
- Use dot notation to query nested fields:
UserInformation.UserName
Conclusion
MongoDB's hierarchical JSON structure allows you to model complex relationships within documents using nested objects and arrays. This eliminates the need for multiple collections and joins in many scenarios.
Advertisements
