Querying on an array of objects for specific nested documents with MongoDB?

To query on an array of objects for nested documents in MongoDB, use the find() method with the $elemMatch operator in projection to return only matching array elements.

Syntax

db.collection.find(
    {},
    {
        arrayField: {
            $elemMatch: { condition }
        }
    }
);

Sample Data

db.demo763.insertOne({
    _id: 1,
    CountryName: "US",
    "studentInformation": [
        {
            StudentName: "Chris"
        },
        {
            StudentName: "David",
            StudentAge: 22
        }
    ]
});
{ "acknowledged": true, "insertedId": 1 }

Display all documents from a collection with the help of find() method ?

db.demo763.find();
{ "_id": 1, "CountryName": "US", "studentInformation": [ { "StudentName": "Chris" }, { "StudentName": "David", "StudentAge": 22 } ] }

Example: Query for Students with Age Field

Following is how to query an array of objects to fetch specific nested documents ?

db.demo763.find({},
{
    studentInformation: {
        $elemMatch: {
            StudentAge: {
                $exists: true
            }
        }
    }
});
{ "_id": 1, "studentInformation": [ { "StudentName": "David", "StudentAge": 22 } ] }

Key Points

  • $elemMatch in projection returns only the first matching array element
  • $exists: true filters for documents where the specified field exists
  • Use empty query {} to match all documents, then filter array elements in projection

Conclusion

Use $elemMatch in projection to query and return specific nested documents from arrays. This approach filters array elements based on conditions while preserving the document structure.

Updated on: 2026-03-15T03:57:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements