使用MongoDB中每个组的最小值和显示计数来聚合组



我有一个包含以下内容的表ProdTable:ProdName PrdCategory PrdPricePrdB 34 8PrdA 34 50PrdC 134 49PrdC 134 50
PrdD 34 8

我想接收MongoDB Collection的输出(相同内容(ProdCategory最小(PrdPrice(计数34 8 2134 49 1

我将如何编写数据库。ProdTable。总数的

答案如下:

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 }
]

最新更新