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.

Updated on: 2026-03-15T01:03:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements