Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs 菜单
Docs 主页
/ /
表达式

$bottomN(表达式操作符)

$bottomN

8.3版本新增

根据指定的排序顺序返回大量的最后 n 个元素。如果大量包含的元素少于 n 个,$bottomN 将返回大量中的所有元素。

注意

消歧

本页介绍$bottomN 表达式操作符。关于$bottomN 累加器操作符,请参阅 $bottomN(累加器操作符)。

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

{
$bottomN:
{
n: <expression>,
sortBy: { <field1>: <sort order>, <field2>: <sort order> ... },
input: <expression>
}
}
字段
必要性
说明

n

必需

要返回的大量元素的数量。

sortBy

必需

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

输入

必需

$bottomN 评估的大量。

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会出错。

以下示例使用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大量上使用 $bottomN

db.movies.aggregate([
{
$match: { title: "The Godfather" }
},
{
$project: {
_id: 0,
title: 1,
lastThreeCastMembersAlphabetically: {
$bottomN: {
n: 3,
sortBy: 1,
input: "$cast"
}
}
}
}
])
[
{
title: 'The Godfather',
lastThreeCastMembersAlphabetically: [ 'James Caan', 'Marlon Brando', 'Richard S. Castellano' ]
}
]

在此示例中,$bottomN 按字母升序对现有 cast大量进行排序,并返回最后三个值。

在此页面上