MongoDB query to access an object in an array

To access an object in an array in MongoDB, use dot notation to specify the field path. This allows you to query nested objects within arrays and retrieve documents that match specific criteria.

Syntax

db.collection.find({"arrayField.objectField": "value"})

Sample Data

db.demo299.insertMany([
    {
        "id": 100,
        "Name": "Robert",
        "details": [
            {
                "SubjectName": ["C++", "Python"]
            },
            {
                "SubjectName": ["Spring", "Hibernate"]
            }
        ]
    },
    {
        "id": 101,
        "Name": "Adam",
        "details": [
            {
                "SubjectName": ["Python", "JSP"]
            },
            {
                "SubjectName": ["Servlet", "Operating System"]
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("5e4d685a5d93261e4bc9ea4b"),
        "1": ObjectId("5e4d685b5d93261e4bc9ea4c")
    }
}

Display All Documents

db.demo299.find();
{
    "_id": ObjectId("5e4d685a5d93261e4bc9ea4b"), "id": 100, "Name": "Robert", "details": [
        { "SubjectName": [ "C++", "Python" ] },
        { "SubjectName": [ "Spring", "Hibernate" ] }
    ]
}
{
    "_id": ObjectId("5e4d685b5d93261e4bc9ea4c"), "id": 101, "Name": "Adam", "details": [
        { "SubjectName": [ "Python", "JSP" ] }, 
        { "SubjectName": [ "Servlet", "Operating System" ] }
    ]
}

Example: Access Object in Array

Find documents where the details array contains an object with "Servlet" in the SubjectName field ?

db.demo299.find({"details.SubjectName": "Servlet"});
{
    "_id": ObjectId("5e4d685b5d93261e4bc9ea4c"), "id": 101, "Name": "Adam", "details": [
        { "SubjectName": [ "Python", "JSP" ] }, 
        { "SubjectName": [ "Servlet", "Operating System" ] }
    ]
}

Key Points

  • Use dot notation to access fields within array objects: "arrayField.objectField"
  • MongoDB automatically searches through all objects in the array for matches
  • Returns the entire document when any array object matches the query criteria

Conclusion

Dot notation provides a simple way to query objects within arrays in MongoDB. Use the format arrayField.objectField to access nested properties and filter documents based on array content.

Updated on: 2026-03-15T02:20:36+05:30

583 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements