How to read a specific key-value pair from a MongoDB collection?

To read a specific key-value pair from a MongoDB collection, use dot notation in the projection parameter of the find() method. This allows you to retrieve only the nested fields you need.

Syntax

db.collection.find(
    {},
    { "parentField.childField": 1 }
);

Sample Data

db.readSpecificKeyValueDemo.insertOne({
    "_id": 100,
    "StudentDetails": {
        "StudentFirstName": "David",
        "StudentLastName": "Miller",
        "StudentAge": 23,
        "StudentCountryName": "US"
    }
});
{ "acknowledged": true, "insertedId": 100 }

Example: Read Specific Nested Field

To retrieve only the StudentCountryName from the nested StudentDetails object ?

db.readSpecificKeyValueDemo.find(
    {},
    { "StudentDetails.StudentCountryName": 1 }
);
{ "_id": 100, "StudentDetails": { "StudentCountryName": "US" } }

Verify Complete Document

Display the full document to see the complete structure ?

db.readSpecificKeyValueDemo.find();
{
    "_id": 100,
    "StudentDetails": {
        "StudentFirstName": "David",
        "StudentLastName": "Miller",
        "StudentAge": 23,
        "StudentCountryName": "US"
    }
}

Key Points

  • Use dot notation with quotes: "parentField.childField": 1
  • The _id field is included by default unless explicitly excluded with "_id": 0
  • Only the projected fields and their parent hierarchy are returned

Conclusion

Dot notation in MongoDB projections allows precise retrieval of nested key-value pairs. Use { "parent.child": 1 } to extract specific fields from embedded documents efficiently.

Updated on: 2026-03-15T00:48:54+05:30

975 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements