Access objects from the nested objects structure in MongoDB

To access objects from nested objects structure in MongoDB, use dot notation to traverse through multiple levels of nested documents. This allows you to query and retrieve documents based on deeply nested field values.

Syntax

db.collection.find({
    "parentObject.childObject.nestedField": "value"
});

Create Sample Data

Let us first create a collection with nested documents ?

db.nestedObjectDemo.insertOne({
    "Student": {
        "StudentDetails": {
            "StudentPersonalDetails": {
                "StudentName": ["John"],
                "StudentCountryName": ["US"],
                "StudentCoreSubject": ["C", "Java"],
                "StudentProject": ["Online Book Store", "Pig Dice Game"]
            }
        }
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c99dfc2863d6ffd454bb650")
}

Display All Documents

View the complete document structure using find() method ?

db.nestedObjectDemo.find().pretty();
{
    "_id": ObjectId("5c99dfc2863d6ffd454bb650"),
    "Student": {
        "StudentDetails": {
            "StudentPersonalDetails": {
                "StudentName": ["John"],
                "StudentCountryName": ["US"],
                "StudentCoreSubject": ["C", "Java"],
                "StudentProject": ["Online Book Store", "Pig Dice Game"]
            }
        }
    }
}

Access Nested Objects Using Dot Notation

Query documents by accessing deeply nested fields with dot notation ?

db.nestedObjectDemo.find({
    "Student.StudentDetails.StudentPersonalDetails.StudentName": "John"
}).pretty();
{
    "_id": ObjectId("5c99dfc2863d6ffd454bb650"),
    "Student": {
        "StudentDetails": {
            "StudentPersonalDetails": {
                "StudentName": ["John"],
                "StudentCountryName": ["US"],
                "StudentCoreSubject": ["C", "Java"],
                "StudentProject": ["Online Book Store", "Pig Dice Game"]
            }
        }
    }
}

Key Points

  • Use dot notation to traverse nested object hierarchy: parent.child.grandchild
  • Enclose the entire field path in quotes when used as query conditions
  • Works with arrays inside nested objects for matching array elements

Conclusion

Dot notation provides a simple way to access deeply nested objects in MongoDB. Use the full path from parent to target field separated by dots to query nested document structures effectively.

Updated on: 2026-03-15T00:28:22+05:30

772 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements