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 reach subdata in MongoDB and display a particular document?
To reach subdata in MongoDB and display a particular document, use dot notation to access nested fields. This allows you to query specific values within nested objects and retrieve matching documents.
Syntax
db.collection.find({"parentField.childField.subField": "value"});
Sample Data
Let us create a collection with nested documents ?
db.demo450.insertMany([
{"Information": {"StudentDetails": {"StudentName": "Chris", "StudentAge": 21}}},
{"Information": {"StudentDetails": {"StudentName": "David", "StudentAge": 23}}},
{"Information": {"StudentDetails": {"StudentName": "Mike", "StudentAge": 22}}}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e7b590e71f552a0ebb0a6e6"),
ObjectId("5e7b591a71f552a0ebb0a6e7"),
ObjectId("5e7b592271f552a0ebb0a6e8")
]
}
Display all documents from the collection ?
db.demo450.find();
{ "_id": ObjectId("5e7b590e71f552a0ebb0a6e6"), "Information": { "StudentDetails": { "StudentName": "Chris", "StudentAge": 21 } } }
{ "_id": ObjectId("5e7b591a71f552a0ebb0a6e7"), "Information": { "StudentDetails": { "StudentName": "David", "StudentAge": 23 } } }
{ "_id": ObjectId("5e7b592271f552a0ebb0a6e8"), "Information": { "StudentDetails": { "StudentName": "Mike", "StudentAge": 22 } } }
Example: Query Subdata Using Dot Notation
Find the document where the nested StudentName is "David" ?
db.demo450.find({"Information.StudentDetails.StudentName": "David"});
{ "_id": ObjectId("5e7b591a71f552a0ebb0a6e7"), "Information": { "StudentDetails": { "StudentName": "David", "StudentAge": 23 } } }
Key Points
- Use dot notation to access nested fields:
"parentField.childField" - MongoDB traverses the document hierarchy using the specified path
- This method works for any level of nesting depth
Conclusion
Dot notation provides a simple way to query nested documents in MongoDB. Use the full path from parent to target field to retrieve specific documents based on subdata values.
Advertisements
