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
Find inside a hash MongoDB?
To find inside a hash (embedded document) in MongoDB, use dot notation to access nested fields. This allows you to query specific fields within embedded documents using the format "parentField.childField".
Syntax
db.collection.find({
"embeddedDocument.field": "value"
});
Sample Data
Let us create a collection with documents containing embedded ClientDetails ?
db.hashDemo.insertMany([
{
"ClientName": "Larry",
"ClientAge": 23,
"ClientDetails": {
"isEducated": true,
"ClientProject": "University Management"
}
},
{
"ClientName": "Chris",
"ClientAge": 26,
"ClientDetails": {
"isEducated": false,
"ClientProject": "Online Book Store"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ca1ef1266324ffac2a7dc5e"),
ObjectId("5ca1ef7766324ffac2a7dc5f")
]
}
Display All Documents
db.hashDemo.find().pretty();
{
"_id": ObjectId("5ca1ef1266324ffac2a7dc5e"),
"ClientName": "Larry",
"ClientAge": 23,
"ClientDetails": {
"isEducated": true,
"ClientProject": "University Management"
}
}
{
"_id": ObjectId("5ca1ef7766324ffac2a7dc5f"),
"ClientName": "Chris",
"ClientAge": 26,
"ClientDetails": {
"isEducated": false,
"ClientProject": "Online Book Store"
}
}
Example: Query Embedded Fields
Find clients who are not educated and work on "Online Book Store" project ?
db.hashDemo.find({
"ClientDetails.isEducated": false,
"ClientDetails.ClientProject": "Online Book Store"
}).pretty();
{
"_id": ObjectId("5ca1ef7766324ffac2a7dc5f"),
"ClientName": "Chris",
"ClientAge": 26,
"ClientDetails": {
"isEducated": false,
"ClientProject": "Online Book Store"
}
}
Conclusion
Use dot notation to query nested fields in MongoDB embedded documents. This enables precise filtering based on specific fields within hash-like structures without retrieving the entire document first.
Advertisements
