How to only get the data of the nested JSON object in MongoDB?

To get the data of the nested JSON object in MongoDB, use findOne() with projection and the $elemMatch operator to filter and return only specific nested array elements.

Syntax

db.collection.findOne(
    { "matchField": "value" },
    { "arrayField": { $elemMatch: { "nestedField": "value" } } }
);

Sample Data

db.demo109.insertOne({
    "Name": "Chris",
    "Subjects": [
        {
            "Id": "100",
            "Name": "MySQL",
            "InstructorDetails": [
                {
                    "Name": "John"
                }
            ]
        },
        {
            "Id": "101",
            "Name": "MongoDB",
            "InstructorDetails": [
                {
                    "Name": "Mike"
                }
            ]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e2ee7df9fd5fd66da21447a")
}

Display All Documents

db.demo109.find();
{
    "_id": ObjectId("5e2ee7df9fd5fd66da21447a"), 
    "Name": "Chris", 
    "Subjects": [
        { "Id": "100", "Name": "MySQL", "InstructorDetails": [ { "Name": "John" } ] },
        { "Id": "101", "Name": "MongoDB", "InstructorDetails": [ { "Name": "Mike" } ] }
    ] 
}

Get Specific Nested Object

To retrieve only the nested object with Id "100" from the Subjects array ?

db.demo109.findOne(
    { "Name": "Chris" },
    { "Subjects": { $elemMatch: { "Id": "100" } } }
);
{
    "_id": ObjectId("5e2ee7df9fd5fd66da21447a"),
    "Subjects": [
        {
            "Id": "100",
            "Name": "MySQL",
            "InstructorDetails": [
                {
                    "Name": "John"
                }
            ]
        }
    ]
}

Key Points

  • $elemMatch returns only the first matching element from the array
  • Use projection (second parameter) to limit which fields are returned
  • The query condition (first parameter) filters documents, while projection filters fields within matched documents

Conclusion

Use findOne() with $elemMatch in the projection parameter to extract specific nested objects from arrays. This approach filters both the document and the nested array elements efficiently.

Updated on: 2026-03-15T01:55:57+05:30

993 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements