我在我的数据库中有一个集合,并且我成功地编写了一个返回这种结果的聚合管道:
ip, type, count
其中ip, type是我分组的字段,count是在我的集合中找到的这些对的数量。
我现在如何只保留对ip, type,其中count是最大的所有ips?
例如:
ip1, type1, 10
ip1, type2, 20
ip1, type3, 30
ip2, type1, 30
ip2, type2, 10从这3,我只想保持ip1,type3,因为30是最大的所有类型的ip1和ip2,type1,因为30是最大的所有类型的ip2。
发布于 2019-12-27 16:15:38
您需要运行另一个$group才能获得maxCount。可以使用$$ROOT变量捕获属于单个组的所有文档。然后,您可以运行$filter来查找值最高的文档,并使用$replaceRoot将该文档提升到结果的根级:
db.collection.aggregate([
{
$group: {
_id: "$_id.ip",
docs: { $push: "$$ROOT" },
maxCount: { $max: "$count" }
}
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: [ { "$filter": { input: "$docs", cond: { $eq: [ "$$this.count", "$maxCount" ] } } } ,0]
}
}
}
])https://stackoverflow.com/questions/59503281
复制相似问题