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
Make nested queries in MongoDB 4 to fetch a specific document
To make nested queries in MongoDB 4 to fetch a specific document, use dot notation to traverse through nested objects and arrays. This allows you to query deeply nested fields within documents.
Syntax
db.collection.find({ "parentField.childField.nestedField": "value" });
Sample Data
Let us first create a collection with nested documents ?
db.demo492.insertMany([
{
"ProductDetails": {
"StockDetails": [
{ "ProductName": "Product-1" },
{ "ProductName": "Product-2" },
{ "ProductName": "Product-3" }
]
}
},
{
"ProductDetails": {
"StockDetails": [
{ "ProductName": "Product-4" },
{ "ProductName": "Product-5" },
{ "ProductName": "Product-6" }
]
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e849db8b0f3fa88e22790c2"),
ObjectId("5e849dceb0f3fa88e22790c3")
]
}
Display all documents from the collection ?
db.demo492.find();
{
"_id": ObjectId("5e849db8b0f3fa88e22790c2"),
"ProductDetails": {
"StockDetails": [
{ "ProductName": "Product-1" },
{ "ProductName": "Product-2" },
{ "ProductName": "Product-3" }
]
}
}
{
"_id": ObjectId("5e849dceb0f3fa88e22790c3"),
"ProductDetails": {
"StockDetails": [
{ "ProductName": "Product-4" },
{ "ProductName": "Product-5" },
{ "ProductName": "Product-6" }
]
}
}
Example: Nested Query Using Dot Notation
To fetch documents containing "Product-1" in the nested array ?
db.demo492.find({ "ProductDetails.StockDetails.ProductName": "Product-1" });
{
"_id": ObjectId("5e849db8b0f3fa88e22790c2"),
"ProductDetails": {
"StockDetails": [
{ "ProductName": "Product-1" },
{ "ProductName": "Product-2" },
{ "ProductName": "Product-3" }
]
}
}
Key Points
- Use dot notation to traverse nested objects and arrays
- MongoDB automatically searches through array elements when querying nested arrays
- The query returns the entire document that contains the matching nested field
Conclusion
Nested queries in MongoDB use dot notation to access deeply nested fields. This powerful feature allows you to query complex document structures efficiently by specifying the complete path to the target field.
Advertisements
