定义
语法
用作表达式操作符符时,$top 的语法如下:
{ $top: { sortBy: <expression>, input: <expression> } }
行为
排序行为
MongoDB根据 sortBy 值对 input大量进行排序。下表提供了不同排序选项的示例:
input | sortBy | 已排序 input | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| | ||||||||||
|
| | ||||||||||
|
| |
Input Values
input字段必须解析为大量。如果指定的 input 不是大量,则MongoDB会出错。
例子
以下示例使用movies sample_mflix示例数据集中的 集合。有关如何将此数据集加载到部署中的详细信息,请参阅加载示例数据集。
movies集合包含类似于以下示例的文档:
{ _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, ... }
以下聚合管道使用 cast大量上的 $top 来按字母顺序返回指定电影的第一个演员:
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大量进行排序并返回第一个值。