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
Search a sub-field on MongoDB?
To search a sub-field in MongoDB, use dot notation with the field path enclosed in double quotes. This allows you to query nested fields within embedded documents.
Syntax
db.collection.find({"parentField.subField": "value"});
Sample Data
db.searchSubFieldDemo.insertMany([
{
"UserDetails": {
"UserEmailId": "John123@gmail.com",
"UserAge": 21
}
},
{
"UserDetails": {
"UserEmailId": "Carol@yahoo.com",
"UserAge": 26
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd3d909edc6604c74817ce2"),
ObjectId("5cd3d9a4edc6604c74817ce3")
]
}
View All Documents
db.searchSubFieldDemo.find();
{
"_id": ObjectId("5cd3d909edc6604c74817ce2"),
"UserDetails": {
"UserEmailId": "John123@gmail.com",
"UserAge": 21
}
}
{
"_id": ObjectId("5cd3d9a4edc6604c74817ce3"),
"UserDetails": {
"UserEmailId": "Carol@yahoo.com",
"UserAge": 26
}
}
Example: Search by Sub-field
Find the document where UserEmailId is "Carol@yahoo.com" ?
db.searchSubFieldDemo.find({"UserDetails.UserEmailId": "Carol@yahoo.com"});
{
"_id": ObjectId("5cd3d9a4edc6604c74817ce3"),
"UserDetails": {
"UserEmailId": "Carol@yahoo.com",
"UserAge": 26
}
}
Conclusion
Use dot notation with quoted field paths to search nested sub-fields in MongoDB. The syntax "parentField.subField" allows precise querying of embedded document properties.
Advertisements
