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
Query deeply nested Objects in MongoDB
To query deeply nested objects in MongoDB, use dot notation to navigate through multiple levels of embedded documents and arrays. The dot notation allows you to access fields at any depth within the document structure.
Syntax
db.collection.find({"level1.level2.level3.field": "value"});
Sample Data
Let us create a collection with deeply nested documents ?
db.demo350.insertMany([
{
id: 101,
Name: "Chris",
details: [
{
_id: 1,
ClientNumber: "10001",
ClientDetails: [
{
Name: "David",
Age: 29
},
{
Name: "Bob",
Age: 31
}
]
}
]
},
{
id: 102,
Name: "David",
details: [
{
_id: 2,
ClientNumber: "10002",
ClientDetails: [
{
Name: "Carol",
Age: 42
},
{
Name: "John",
Age: 37
}
]
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e553a68f8647eb59e5620b8"),
ObjectId("5e553a8ff8647eb59e5620b9")
]
}
Display all documents from the collection ?
db.demo350.find();
{
"_id": ObjectId("5e553a68f8647eb59e5620b8"),
"id": 101,
"Name": "Chris",
"details": [
{
"_id": 1,
"ClientNumber": "10001",
"ClientDetails": [
{ "Name": "David", "Age": 29 },
{ "Name": "Bob", "Age": 31 }
]
}
]
}
{
"_id": ObjectId("5e553a8ff8647eb59e5620b9"),
"id": 102,
"Name": "David",
"details": [
{
"_id": 2,
"ClientNumber": "10002",
"ClientDetails": [
{ "Name": "Carol", "Age": 42 },
{ "Name": "John", "Age": 37 }
]
}
]
}
Example: Query Deeply Nested Objects
Find documents where a client named "John" exists in the nested ClientDetails array ?
db.demo350.find({"details.ClientDetails.Name": "John"});
{
"_id": ObjectId("5e553a8ff8647eb59e5620b9"),
"id": 102,
"Name": "David",
"details": [
{
"_id": 2,
"ClientNumber": "10002",
"ClientDetails": [
{ "Name": "Carol", "Age": 42 },
{ "Name": "John", "Age": 37 }
]
}
]
}
Key Points
- Use dot notation to traverse nested object hierarchies:
"field1.field2.field3" - MongoDB automatically searches through array elements when querying nested arrays
- The query path must exactly match the document structure
Conclusion
Dot notation provides a simple way to query deeply nested objects in MongoDB. Use the field path syntax to access any level of nested data, and MongoDB will automatically handle array traversal during the search.
Advertisements
