对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$top(表达式操作符)

$top

8.3版本新增。

根据指定的排序顺序返回数组中的顶部元素。

注意

消歧

本页介绍 $top 表达式操作符。您还可以在以下其他场景中使用 $top:

用作表达式操作符时,$top 的语法如下:

{ $top: { sortBy: <expression>, input: <expression> }}
字段
必要性
说明

sortBy

必需

指定结果的顺序。有关 sortBy 值的更多信息,请参阅 排序行为。

输入

必需

$top 评估的数组。

MongoDB根据 sortBy 值对 input数组进行排序。下表提供了不同排序选项的示例:

input
sortBy
已排序 input
[ 8, 3, 1, 10]

1

[1, 3, 8, 10]
[ 8, 3, 1, 10]

-1

[10, 8, 3, 1]
[ { a: 1, b: 1 }, { a: 2, b: 2 }, { a: 2, b: 1 }]

{ a: 1, b: 1 }

[ { a: 1, b: 1 }, { a: 2, b: 1 }, { a: 2, b: 2 }]

input字段必须解析为数组。如果指定的 input 不是数组,则MongoDB会出错。

以下示例使用 sample_mflix 示例数据集中的 movies 集合。有关如何将此数据集加载到部署中的详细信息,请参阅 加载示例数据集。

movies集合包含类似于以下示例的document:

{ _id: ObjectId('573a1396f29313caabce4a9a'), year: 1972, genres: [ 'Crime', 'Drama' ], title: 'The Godfather', cast: [ 'Marlon Brando', 'Al Pacino', 'James Caan', 'Richard S. Castellano' ], directors: [ 'Francis Ford Coppola' ], runtime: 175, ...}

以下聚合管道使用 $top 在 cast 数组上来按字母顺序返回指定电影的第一个演员:

db.movies.aggregate([ { $match: { title: "The Godfather" } }, { $project: { _id: 0, title: 1, firstCastMemberAlphabetically: { $top: { sortBy: 1, input: "$cast" } } } }])
[ { title: 'The Godfather', firstCastMemberAlphabetically: 'Al Pacino' }]

在此示例中,$top 按字母升序对现有 cast数组进行排序并返回第一个值。

给本页内容打分