Aggregate Group by using minimum value and display count for each group at MongoDB

Viewed 16

I have a table ProdTable with following content: ProdName PrdCategory PrdPrice PrdB 34 8 PrdA 34 50 PrdC 134 49 PrdC 134 50
PrdD 34 8

I want to receive the output from MongoDB Collection (same content) ProdCategory min(PrdPrice) count 34 8 2 134 49 1

How will I write my db.ProdTable.Aggregate?

1 Answers

Here is the answer:

db.products.aggregate([
   { $group: { _id: "$ProdCategory", minPrice: { $min: "$ProdPrice" }, prices: { $push: "$ProdPrice" } } }, 
   { $unwind: "$prices" }, 
   { $match: { $expr: { $eq: ["$prices", "$minPrice"] } } }, 
   { $group: { _id: "$_id", minPrice: { $min: "$minPrice" }, count: { $sum: 1 } } } 
])

And my expected answer works like a charm, as shown below! Thanks Duncan.
 [
   { _id: 134, minPrice: 49, count: 1 },
   { _id: 34, minPrice: 8, count: 2 }
 ]
Related