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
Grouping the array items in MongoDB and get the count the products with similar price?
To group array items in MongoDB and count products with similar prices, use the $unwind operator to flatten the array, then $group by price and $sum to count occurrences.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $group: {
"_id": "$arrayField.fieldToGroupBy",
"count": { $sum: 1 }
}},
{ $sort: { "_id": 1 } }
])
Sample Data
db.products.insertOne({
"ProductInformation": [
{
"ProductName": "Product-1",
"ProductPrice": 100
},
{
"ProductName": "Product-2",
"ProductPrice": 1100
},
{
"ProductName": "Product-3",
"ProductPrice": 100
},
{
"ProductName": "Product-4",
"ProductPrice": 1100
},
{
"ProductName": "Product-5",
"ProductPrice": 100
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e908e2339cfeaaf0b97b57a")
}
Verify Sample Data
db.products.find();
{
"_id": ObjectId("5e908e2339cfeaaf0b97b57a"),
"ProductInformation": [
{ "ProductName": "Product-1", "ProductPrice": 100 },
{ "ProductName": "Product-2", "ProductPrice": 1100 },
{ "ProductName": "Product-3", "ProductPrice": 100 },
{ "ProductName": "Product-4", "ProductPrice": 1100 },
{ "ProductName": "Product-5", "ProductPrice": 100 }
]
}
Group Array Items by Price
db.products.aggregate([
{
"$unwind": "$ProductInformation"
},
{
"$group": {
"_id": "$ProductInformation.ProductPrice",
"count": { "$sum": 1 }
}
},
{ "$sort": { "_id": 1 } }
]);
{ "_id": 100, "count": 3 }
{ "_id": 1100, "count": 2 }
How It Works
-
$unwindconverts each array element into a separate document -
$groupgroups documents by ProductPrice and counts using$sum: 1 -
$sortorders results by price in ascending order
Conclusion
Use $unwind to flatten arrays, then $group with $sum: 1 to count items with similar values. This aggregation pipeline effectively groups and counts products by price.
Advertisements
