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
Retrieve values from nested JSON array in MongoDB?
To retrieve values from nested JSON array in MongoDB, use dot notation to navigate through the nested structure. This allows you to query specific fields within arrays and embedded documents.
Syntax
db.collectionName.find({
"outerField.arrayField.nestedField": "value"
});
Sample Data
Let us create a collection with nested JSON array documents ?
db.nestedJSONArrayDemo.insertMany([
{
"ClientDetails": {
"ClientPersonalDetails": [
{ "CountryName": "US" },
{ "CountryName": "AUS" },
{ "ClientName": "Chris" },
{ "ClientName": "David" }
]
}
},
{
"ClientDetails": {
"ClientPersonalDetails": [
{ "CountryName": "Belgium" },
{ "CountryName": "Canada" },
{ "CountryName": "Egypt" }
]
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd2cbb2b64f4b851c3a13bc"),
ObjectId("5cd2cc14b64f4b851c3a13bd")
]
}
View All Documents
db.nestedJSONArrayDemo.find().pretty();
{
"_id": ObjectId("5cd2cbb2b64f4b851c3a13bc"),
"ClientDetails": {
"ClientPersonalDetails": [
{ "CountryName": "US" },
{ "CountryName": "AUS" },
{ "ClientName": "Chris" },
{ "ClientName": "David" }
]
}
}
{
"_id": ObjectId("5cd2cc14b64f4b851c3a13bd"),
"ClientDetails": {
"ClientPersonalDetails": [
{ "CountryName": "Belgium" },
{ "CountryName": "Canada" },
{ "CountryName": "Egypt" }
]
}
}
Example: Query Nested Array Field
Retrieve documents where any array element has CountryName "Canada" ?
db.nestedJSONArrayDemo.find({
"ClientDetails.ClientPersonalDetails.CountryName": "Canada"
});
{
"_id": ObjectId("5cd2cc14b64f4b851c3a13bd"),
"ClientDetails": {
"ClientPersonalDetails": [
{ "CountryName": "Belgium" },
{ "CountryName": "Canada" },
{ "CountryName": "Egypt" }
]
}
}
Key Points
- Use dot notation to traverse nested objects and arrays
- MongoDB automatically searches all array elements for matching values
- The query returns the entire document if any array element matches
Conclusion
Dot notation provides a simple way to query nested JSON arrays in MongoDB. Use the pattern outerField.arrayField.nestedField to search for specific values within nested structures.
Advertisements
