Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieve values from nested JSON array in MongoDB?
To retrieve values from nested JSON array, you can use the below syntax −
db.yourCollectionName.find({"yourOuterFieldName.yourInnerFieldName.yourNextInnerFieldName…...N": "yourValue"}).pretty();
Let us first create a collection with documents −
> db.nestedJSONArrayDemo.insertOne({
... "ClientDetails" :
... {
... "ClientPersonalDetails" : [
... { "CountryName" : "US" },
... { "CountryName" : "AUS"},
... { "ClientName":"Chris" },
... { "ClientName":"David" }
... ]
... }
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2cbb2b64f4b851c3a13bc")
}
> db.nestedJSONArrayDemo.insertOne({
... "ClientDetails" :
... {
... "ClientPersonalDetails" : [
... { "CountryName" : "Belgium" },
... { "CountryName" : "Canada"},
... { "CountryName" : "Egypt"},
... ]
... }
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2cc14b64f4b851c3a13bd")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.nestedJSONArrayDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd2cbb2b64f4b851c3a13bc"),
"ClientDetails" : {
"ClientPersonalDetails" : [
{
"CountryName" : "US"
},
{
"CountryName" : "AUS"
},
{
"ClientName" : "Chris"
},
{
"ClientName" : "David"
}
]
}
}
{
"_id" : ObjectId("5cd2cc14b64f4b851c3a13bd"),
"ClientDetails" : {
"ClientPersonalDetails" : [
{
"CountryName" : "Belgium"
},
{
"CountryName" : "Canada"
},
{
"CountryName" : "Egypt"
}
]
}
}
Following is the query to retrieve values from nested JSON array in MongoDB −
> db.nestedJSONArrayDemo.find({"ClientDetails.ClientPersonalDetails.CountryName": "Canada"}).pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd2cc14b64f4b851c3a13bd"),
"ClientDetails" : {
"ClientPersonalDetails" : [
{
"CountryName" : "Belgium"
},
{
"CountryName" : "Canada"
},
{
"CountryName" : "Egypt"
}
]
}
}Advertisements