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 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
1includes it in the result,0excludes it - The
_idfield 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.
Advertisements
