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
Accessing array values in a MongoDB collection to fetch a specific document
To access array values in MongoDB and fetch a specific document, use dot notation to query nested fields within arrays. This allows you to search for documents containing specific values in their array elements.
Syntax
db.collection.find({ "arrayName.fieldName": "value" });
Sample Data
Let us create a collection with documents containing ProductDetails arrays ?
db.demo326.insertMany([
{
"id": 101,
"ProductDetails": [
{ "ProductId": "Prod-101", "ProductName": "Product-1" },
{ "ProductId": "Prod-102", "ProductName": "Product-2" }
]
},
{
"id": 103,
"ProductDetails": [
{ "ProductId": "Prod-104", "ProductName": "Product-5" },
{ "ProductId": "Prod-105", "ProductName": "Product-6" }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e516751f8647eb59e562074"),
ObjectId("5e516771f8647eb59e562075")
]
}
Display All Documents
db.demo326.find();
{
"_id": ObjectId("5e516751f8647eb59e562074"),
"id": 101,
"ProductDetails": [
{ "ProductId": "Prod-101", "ProductName": "Product-1" },
{ "ProductId": "Prod-102", "ProductName": "Product-2" }
]
}
{
"_id": ObjectId("5e516771f8647eb59e562075"),
"id": 103,
"ProductDetails": [
{ "ProductId": "Prod-104", "ProductName": "Product-5" },
{ "ProductId": "Prod-105", "ProductName": "Product-6" }
]
}
Access Array Values to Fetch Specific Document
Query to find the document containing ProductId "Prod-104" within the ProductDetails array ?
db.demo326.find({ "ProductDetails.ProductId": "Prod-104" });
{
"_id": ObjectId("5e516771f8647eb59e562075"),
"id": 103,
"ProductDetails": [
{ "ProductId": "Prod-104", "ProductName": "Product-5" },
{ "ProductId": "Prod-105", "ProductName": "Product-6" }
]
}
Conclusion
Use dot notation with array field names to query nested values in MongoDB arrays. The syntax "arrayName.fieldName" matches documents containing the specified value in any array element, returning the entire matching document.
Advertisements
