定义
返回特定窗口中的文档数。
注意
消歧
本页介绍了用作窗口函数的 $count。
您还可以在其他上下文中使用 $count:
$count (accumulator),返回群组中的文档数。$count (aggregation stage),返回输入文档的数量。
语法
{ $setWindowFields: { ... output: { <field>: { $count: {}, window: { documents: [ <lower boundary>, <upper boundary> ] } } } } }
$count 不接受任何参数。
提示
$count 在功能上等同于在 $setWindowFields 阶段使用 { $sum: 1 }。
例子
本页上的示例使用 sample_mflix 数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载样本数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。
计算具有相似评分的电影
此示例使用 $count窗口函数和基于范围的窗口来计算有多少部来自 2000 的动作片的 IMDb 评分在每部电影评分的 0.5 点以内。
db.movies.aggregate( [ { $match: { genres: "Action", year: 2000, "imdb.rating": { $ne: null } } }, { $setWindowFields: { sortBy: { "imdb.rating": 1 }, output: { moviesWithSimilarRating: { $count: {}, window: { range: [ -0.5, 0.5 ] } } } } }, { $project: { _id: 0, title: 1, "imdb.rating": 1, moviesWithSimilarRating: 1 } }, { $sort: { "imdb.rating": -1 } }, { $limit: 10 } ] )
在前面的示例中:
$match过滤 2000 上映且具有imdb.rating值的动作片。sortBy: { "imdb.rating": 1 }按 IMDb 评级升序对文档进行排序。使用基于范围的窗口时需要sortBy。$project在输出中包含title、imdb.rating和moviesWithSimilarRating字段。$sort和$limit返回评分最高的 10 电影,以方便阅读。
输出显示,具有相对独特评分的《角斗士》(8.5) 的 moviesWithSimilarRating 计数低于具有更常见评分(例如 7.4)的电影。