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 in a dictionary like structure by value with MongoDB?
To find documents in a dictionary-like structure by value in MongoDB, use dot notation to specify the exact path to the nested field you want to search.
Syntax
db.collection.find({
"parentObject.nestedObject.fieldName": "searchValue"
});
Sample Data
Let us first create a collection with nested dictionary-like documents :
db.findInDictionaryDemo.insertMany([
{
"_id": 101,
"AllCustomerDetails": {
"SomeCustomerDetail1": {
"CustomerName1": "John Doe",
"CustomerName2": "John Smith"
},
"SomeCustomerDetail2": {
"CustomerName1": "Carol Taylor",
"CustomerName2": "David Miller"
}
}
},
{
"_id": 102,
"AllCustomerDetails": {
"SomeCustomerDetail1": {
"CustomerName1": "Sam Williams",
"CustomerName2": "Bob Johnson"
},
"SomeCustomerDetail2": {
"CustomerName1": "Chris Brown",
"CustomerName2": "Mike Wilson"
}
}
}
]);
{
"acknowledged": true,
"insertedIds": [101, 102]
}
Display All Documents
db.findInDictionaryDemo.find().pretty();
{
"_id": 101,
"AllCustomerDetails": {
"SomeCustomerDetail1": {
"CustomerName1": "John Doe",
"CustomerName2": "John Smith"
},
"SomeCustomerDetail2": {
"CustomerName1": "Carol Taylor",
"CustomerName2": "David Miller"
}
}
}
{
"_id": 102,
"AllCustomerDetails": {
"SomeCustomerDetail1": {
"CustomerName1": "Sam Williams",
"CustomerName2": "Bob Johnson"
},
"SomeCustomerDetail2": {
"CustomerName1": "Chris Brown",
"CustomerName2": "Mike Wilson"
}
}
}
Find by Nested Value
Search for documents where CustomerName2 in SomeCustomerDetail2 equals "Mike Wilson" :
db.findInDictionaryDemo.find({
"AllCustomerDetails.SomeCustomerDetail2.CustomerName2": "Mike Wilson"
}).pretty();
{
"_id": 102,
"AllCustomerDetails": {
"SomeCustomerDetail1": {
"CustomerName1": "Sam Williams",
"CustomerName2": "Bob Johnson"
},
"SomeCustomerDetail2": {
"CustomerName1": "Chris Brown",
"CustomerName2": "Mike Wilson"
}
}
}
Key Points
- Use dot notation to traverse nested objects: "parent.child.field"
- MongoDB searches the exact field path specified in the query
- Field names are case-sensitive in the dot notation path
Conclusion
MongoDB's dot notation allows precise querying of nested dictionary-like structures by specifying the complete path to the target field. This enables efficient searches within complex document hierarchies.
Advertisements
