MongoDB query to fetch array values

To fetch specific array values in MongoDB, use the find() method along with $elemMatch operator to match documents containing specific values in nested arrays.

Syntax

db.collection.find({
    "arrayField": {
        $elemMatch: {
            "nestedField": "matchValue"
        }
    }
});

Sample Data

db.fetchingArrayValuesDemo.insertMany([
    {
        "StudentName": "David",
        "StudentDetails": [
            {
                "FatherName": "Bob",
                "CountryName": "US",
                "Favourite": [
                    {
                        "Teacher": "DAVID",
                        "Subject": ["MySQL", "MongoDB", "Java"],
                        "Marks": [50, 60, 65]
                    }
                ]
            }
        ]
    },
    {
        "StudentName": "Robert",
        "StudentDetails": [
            {
                "FatherName": "Sam",
                "CountryName": "AUS",
                "Favourite": [
                    {
                        "Teacher": "MIKE",
                        "Subject": ["Python", "C", "C++"],
                        "Marks": [76, 89, 91]
                    }
                ]
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e06fc3425ddae1f53b621fa"),
        ObjectId("5e06fc6825ddae1f53b621fb")
    ]
}

Example: Fetch Documents by Array Values

Query to find students whose favorite teacher is "DAVID" ?

db.fetchingArrayValuesDemo.find({
    "StudentDetails": {
        $elemMatch: {
            "Favourite": {
                $elemMatch: {
                    "Teacher": "DAVID"
                }
            }
        }
    }
});
{
    "_id": ObjectId("5e06fc3425ddae1f53b621fa"),
    "StudentName": "David",
    "StudentDetails": [
        {
            "FatherName": "Bob",
            "CountryName": "US",
            "Favourite": [
                {
                    "Teacher": "DAVID",
                    "Subject": ["MySQL", "MongoDB", "Java"],
                    "Marks": [50, 60, 65]
                }
            ]
        }
    ]
}

Key Points

  • $elemMatch matches documents where at least one array element satisfies all specified conditions.
  • Use nested $elemMatch operators for deeply nested array structures.
  • Returns the entire document, not just the matching array elements.

Conclusion

The $elemMatch operator effectively queries nested arrays in MongoDB. Use multiple $elemMatch operators to navigate through deeply nested array structures and find documents containing specific array values.

Updated on: 2026-03-15T02:06:05+05:30

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements