MongoDB实现Limit with ties功能 动态返回电影数量最高的所有并列年份
MongoDB动态返回电影数量最高并列年份的聚合查询实现
原查询采用固定$limit:3的写法仅能适配当前3个年份并列第一的场景,无法动态适配不同数量的并列情况,可通过多阶段聚合逻辑实现动态匹配:
全版本兼容实现方案
该方案兼容MongoDB 3.2及以上所有版本,无需预设阈值,自动适配任意数量的并列场景:
db.movies.aggregate([ // 按年份分组统计各年份电影总量 { $group: { _id: "$year", movie_count: { $sum: 1 } } }, // 全局聚合拿到最高电影数量,同时暂存所有年份的统计结果 { $group: { _id: null, max_count: { $max: "$movie_count" }, all_year_stats: { $push: { year: "$_id", count: "$movie_count" } } } }, // 拆分年份统计数组为单条文档 { $unwind: "$all_year_stats" }, // 匹配所有电影数量等于最高值的年份 { $match: { $expr: { $eq: ["$all_year_stats.count", "$max_count"] } } }, // 调整输出字段格式,可按需自定义 { $project: { _id: 0, year: "$all_year_stats.year", movie_count: "$all_year_stats.count" } } ])
MongoDB 5.0+优化版本
如果使用MongoDB 5.0及以上版本,可以通过窗口函数$setWindowFields简化查询,性能更优:
db.movies.aggregate([ { $group: { _id: "$year", movie_count: { $sum: 1 } } }, // 窗口函数全局计算最高电影数量 { $setWindowFields: { sortBy: { movie_count: -1 }, output: { max_count: { $max: "$movie_count", window: { documents: ["unbounded", "unbounded"] } } } } }, // 匹配最高数量的年份 { $match: { $expr: { $eq: ["$movie_count", "$max_count"] } } }, { $project: { _id: 0, year: "$_id", movie_count: 1 } } ])
内容的提问来源于stack exchange,提问作者margarita
相关产品推荐
相关产品推荐

