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
Using find() to search for nested keys in MongoDB?
To search for nested keys in MongoDB, use dot notation to specify the path to the nested field. This allows you to query documents based on values within embedded objects.
Syntax
db.collectionName.find({"outerField.innerField": "value"});
Sample Data
Let us create a collection with nested documents ?
db.searchForNestedKeysDemo.insertMany([
{
"ClientName": "Larry",
"ClientAge": 28,
"ClientExtraDetails": {
"isEducated": true,
"CountryName": "US"
}
},
{
"ClientName": "Chris",
"ClientAge": 29,
"ClientExtraDetails": {
"isEducated": false,
"CountryName": "UK"
}
},
{
"ClientName": "David",
"ClientAge": 39,
"ClientExtraDetails": {
"isEducated": true,
"CountryName": "AUS"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ca20e8b66324ffac2a7dc64"),
ObjectId("5ca20ea366324ffac2a7dc65"),
ObjectId("5ca20eba66324ffac2a7dc66")
]
}
Example: Search by Nested Field
Find all clients from the UK using dot notation ?
db.searchForNestedKeysDemo.find({"ClientExtraDetails.CountryName": "UK"});
{
"_id": ObjectId("5ca20ea366324ffac2a7dc65"),
"ClientName": "Chris",
"ClientAge": 29,
"ClientExtraDetails": {
"isEducated": false,
"CountryName": "UK"
}
}
Example: Search by Boolean Nested Field
Find all educated clients ?
db.searchForNestedKeysDemo.find({"ClientExtraDetails.isEducated": true});
{
"_id": ObjectId("5ca20e8b66324ffac2a7dc64"),
"ClientName": "Larry",
"ClientAge": 28,
"ClientExtraDetails": {
"isEducated": true,
"CountryName": "US"
}
}
{
"_id": ObjectId("5ca20eba66324ffac2a7dc66"),
"ClientName": "David",
"ClientAge": 39,
"ClientExtraDetails": {
"isEducated": true,
"CountryName": "AUS"
}
}
Conclusion
Dot notation enables precise querying of nested fields in MongoDB documents. Simply use the format "outerField.innerField" to access and search within embedded objects efficiently.
Advertisements
