How to get the child of a MongoDB collection by the key?

To get the child of a collection in MongoDB by a specific key, use the find() method with projection. This allows you to retrieve only specific nested fields from documents that match your query criteria.

Syntax

db.collection.find(
    { "field": "value" },
    { "nestedObject.key": 1 }
);

Sample Data

db.demo305.insertMany([
    {
        _id: 101,
        FirstName: "Chris",
        details: {
            "0": "102",
            "1": "10001"
        }
    },
    {
        _id: 102,
        FirstName: "David",
        details: {
            "0": "103",
            "1": "10002"
        }
    }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 101,
        "1": 102
    }
}

View Sample Data

db.demo305.find();
{ "_id": 101, "FirstName": "Chris", "details": { "0": "102", "1": "10001" } }
{ "_id": 102, "FirstName": "David", "details": { "0": "103", "1": "10002" } }

Example: Get Specific Child by Key

To get only the child field details.0 from document with _id: 102 ?

db.demo305.find(
    { _id: 102 },
    { "details.0": 1 }
);
{ "_id": 102, "details": { "0": "103" } }

Key Points

  • Use dot notation in projection to access nested object properties
  • Setting field to 1 includes it in the result, 0 excludes it
  • The _id field is included by default unless explicitly excluded

Conclusion

Use MongoDB's projection feature with dot notation to retrieve specific child fields from nested objects. This approach efficiently returns only the required data, reducing bandwidth and improving query performance.

Updated on: 2026-03-15T02:21:41+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements