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
Get specific elements from embedded array in MongoDB?
To get specific elements from an embedded array in MongoDB, use the $unwind operator to deconstruct the array, then $match with dot notation to filter elements based on specific criteria.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.fieldName": value } },
{ $project: { _id: 0, arrayField: 1 } }
]);
Sample Data
db.demo641.insertOne({
ProductId: 101,
"ProductInformation": [
{
ProductName: "Product-1",
"ProductPrice": 1000
},
{
ProductName: "Product-2",
"ProductPrice": 500
},
{
ProductName: "Product-3",
"ProductPrice": 2000
},
{
ProductName: "Product-4",
"ProductPrice": 3000
}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("...") }
Display all documents from the collection ?
db.demo641.find();
{
"_id" : ObjectId("5e9c31d46c954c74be91e6e2"),
"ProductId" : 101,
"ProductInformation" : [
{ "ProductName" : "Product-1", "ProductPrice" : 1000 },
{ "ProductName" : "Product-2", "ProductPrice" : 500 },
{ "ProductName" : "Product-3", "ProductPrice" : 2000 },
{ "ProductName" : "Product-4", "ProductPrice" : 3000 }
]
}
Example: Get Products with Specific Prices
Get products with prices 1000 or 2000 ?
db.demo641.aggregate([
{ $unwind: "$ProductInformation" },
{ $match: { "ProductInformation.ProductPrice": { $in: [1000, 2000] } } },
{ $project: { _id: 0, ProductInformation: 1 } }
]);
{
"ProductInformation" : {
"ProductName" : "Product-1",
"ProductPrice" : 1000
}
}
{
"ProductInformation" : {
"ProductName" : "Product-3",
"ProductPrice" : 2000
}
}
How It Works
-
$unwindcreates a separate document for each array element -
$matchfilters documents based on embedded field values -
$projectshapes the output to show only required fields
Conclusion
Use $unwind followed by $match in an aggregation pipeline to extract specific elements from embedded arrays. This approach allows precise filtering based on nested field values.
Advertisements
