Find the MongoDB document from sub array?

To find documents from a sub array in MongoDB, use dot notation to access nested array elements. This allows you to query specific fields within arrays that are embedded in your documents.

Syntax

db.collection.find({
    "parentField.arrayField.subField": "value"
});

Sample Data

Let us create sample documents with employee appraisal data ?

db.findDocumentDemo.insertMany([
    {
        "EmployeeDetails": {
            "EmployeeAppraisalTime": [
                {"EmployeeDesignation": "Developer", "Salary": 45000},
                {"EmployeeDesignation": "Tester", "Salary": 30000},
                {"EmployeeDesignation": "HR", "Salary": 22000},
                {"EmployeeDesignation": "Accountant", "Salary": 18000}
            ]
        }
    },
    {
        "EmployeeDetails": {
            "EmployeeAppraisalTime": [
                {"EmployeeDesignation": "Developer", "Salary": 105000},
                {"EmployeeDesignation": "Tester", "Salary": 45000},
                {"EmployeeDesignation": "HR", "Salary": 34000},
                {"EmployeeDesignation": "Accountant", "Salary": 24000}
            ]
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd2c0f7b64f4b851c3a13a8"),
        ObjectId("5cd2c1d5b64f4b851c3a13a9")
    ]
}

Example: Query Sub Array Elements

Find documents where the sub array contains Developers with salary of 45000 or 105000 ?

db.findDocumentDemo.find({
    "EmployeeDetails.EmployeeAppraisalTime.EmployeeDesignation": "Developer",
    "EmployeeDetails.EmployeeAppraisalTime.Salary": { "$in": [45000, 105000] }
});
{
    "_id": ObjectId("5cd2c0f7b64f4b851c3a13a8"),
    "EmployeeDetails": {
        "EmployeeAppraisalTime": [
            {"EmployeeDesignation": "Developer", "Salary": 45000},
            {"EmployeeDesignation": "Tester", "Salary": 30000},
            {"EmployeeDesignation": "HR", "Salary": 22000},
            {"EmployeeDesignation": "Accountant", "Salary": 18000}
        ]
    }
}
{
    "_id": ObjectId("5cd2c1d5b64f4b851c3a13a9"),
    "EmployeeDetails": {
        "EmployeeAppraisalTime": [
            {"EmployeeDesignation": "Developer", "Salary": 105000},
            {"EmployeeDesignation": "Tester", "Salary": 45000},
            {"EmployeeDesignation": "HR", "Salary": 34000},
            {"EmployeeDesignation": "Accountant", "Salary": 24000}
        ]
    }
}

Key Points

  • Use dot notation to traverse nested structures: parentField.arrayField.subField
  • The $in operator matches any value from the specified array
  • MongoDB returns the entire matching document, not just the matching array elements

Conclusion

Dot notation provides a simple way to query nested array elements in MongoDB. Combine it with query operators like $in to create flexible searches within sub arrays.

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

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements