Retrieve values from nested JSON array in MongoDB?

MongoDBDatabaseBig Data Analytics

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"
         }
      ]
   }
}
raja
Published on 22-May-2019 14:45:21
Advertisements