Accessing inner element of JSON array in MongoDB?

To access inner element of JSON array in MongoDB, use dot notation to traverse through nested objects and arrays. This allows you to query and filter documents based on deeply nested field values.

Syntax

db.collection.find({"outerObject.arrayField.nestedObject.fieldName": value})

Sample Data

db.demo687.insertMany([
    {
        CountryName: 'US',
        info: {
            id: 101,
            details: [
                {
                    Name: 'Chris',
                    SubjectName: 'MongoDB',
                    otherDetails: {
                        "Marks": 58,
                        Age: 23
                    }
                }
            ]
        }
    },
    {
        CountryName: 'UK',
        info: {
            id: 102,
            details: [
                {
                    Name: 'David',
                    SubjectName: 'MySQL',
                    otherDetails: {
                        "Marks": 78,
                        Age: 21
                    }
                }
            ]
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("...")
    ]
}

Example: Access Inner Array Element

Display all documents from the collection ?

db.demo687.find();
{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }
{ "_id" : ObjectId("5ea55673a7e81adc6a0b3963"), "CountryName" : "UK", "info" : { "id" : 102, "details" : [ { "Name" : "David", "SubjectName" : "MySQL", "otherDetails" : { "Marks" : 78, "Age" : 21 } } ] } }

Find documents where the nested Marks field equals 58 ?

db.demo687.find({"info.details.otherDetails.Marks": 58});
{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }

Key Points

  • Use . (dot) to traverse nested objects and arrays
  • MongoDB automatically searches through array elements when using dot notation
  • The path follows the structure: parentObject.arrayField.nestedField

Conclusion

Dot notation in MongoDB provides a powerful way to access deeply nested elements within JSON arrays. Use the complete path from the root document to target specific nested fields for querying and filtering operations.

Updated on: 2026-03-15T03:37:43+05:30

711 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements