Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
_idfield 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.
Advertisements
