mongodb分组后取前两位
db.getCollection("BarcodeMaster").aggregate([ // 删选条件 { $match: { Status:6, BarcodeType:0, Qty:{$gt:0}, Bin:{$ne:null} } }, // 按料品、仓库、库位分组,统计数量 { $group: { _id: { ItemMaster: "$ItemMaster", Wh: "$Wh", Bin:"$Bin" }, orderCount: { $sum: 1 } } }, // 按照料品、仓库、统计数量降序排,以便后面取数量最大的几个 { $sort: { "_id.ItemMaster": 1, "_id.Wh": 1, "orderCount": -1 } }, // 按照料品、仓库统计,取最多的库位 { $group: { _id: { ItemMaster: "$_id.ItemMaster", Wh: "$_id.Wh" }, topBins: { $push: { Bin: "$_id.Bin", orderCount: "$orderCount" } } } }, // 取库位最大两位 { $project: { topBins: { $slice: ["$topBins", 2] } } }, // 展开 { $unwind: "$topBins" }, // 打印出来显示 { $project: { _id: 0, ItemMaster: "$_id.ItemMaster", Wh: "$_id.Wh", Bin: "$topBins.Bin", OrderCount: "$topBins.orderCount", CreatedOn:new Date() } }, { $out: "ItemMasterWareHouseBin" } ])