对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs 菜单

$count(窗口函数)

$count

返回特定窗口中的文档数。

注意

消歧

本页介绍了用作窗口函数的 $count。

您还可以在其他上下文中使用 $count:

{
$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。

  • output 使用 $count 将 moviesWithSimilarRating字段设立为 IMDb 评级处于当前窗口内的电影数量。

    窗口使用 range: [ -0.5, 0.5 ],其中包括 imdb.rating 在当前文档评分的 0.5 点以内的所有文档。

  • $project 在输出中包含 title、imdb.rating 和 moviesWithSimilarRating 字段。

  • $sort 和 $limit 返回评分最高的 10 电影,以方便阅读。

输出显示,具有相对独特评分的《角斗士》(8.5) 的 moviesWithSimilarRating 计数低于具有更常见评分(例如 7.4)的电影。

给本页内容打分

在此页面上