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

$lastN(累加器运算符)

$lastN

返回对群组中的最后 n 个元素评估指定表达式的结果。结果仅在分组阶段的输入数据具有定义的排序顺序时才有意义。如果该组包含的元素少于 n 个,$lastN 返回该组中的所有元素。

$lastN 累加器可在以下阶段使用:

注意

消歧

本页介绍了 $lastN 用作 累加器 时的情况。累加器对一组输入文档返回聚合值,如总和、最大值或最小值。

您还可以在这些其他上下文中使用 $lastN:

{
$lastN:
{
input: <expression>,
n: <expression>
}
}
字段
类型
说明

input

表达式(expression)

input 表达式对输入组中的每个文档进行求值,并保留最后 n 个结果。

n

表达式(expression)

The number of elements that $lastN returns from the group. For an example of setting n dynamically based on the group key, see Set n Based on the Group Key.

  • $lastN 不筛选空值。

  • $lastN 将缺失值转换为空。

您可以使用 $lastN 和 $bottomN 返回组中的最后 n 个元素。然而,使用它们的时机差异取决于您的输入文档是否已经排序。

  • 如果进入$group的文档已经排序,则应使用$lastN 。

  • 如果您要排序并选择底部的n元素,则可以使用$bottomN通过一个累加器完成这两项任务。

The examples on this page use the movies collection in the sample_mflix sample dataset. To learn how to load the sample dataset into your MongoDB deployment, see Import Sample Data Into Your Atlas Deployment.

您可以使用 $lastN 累加器来查找某一类型中最近发布的电影。

db.movies.aggregate( [
{
$match: { genres: "Horror", year: { $type: "int" } }
},
{
$sort: { year: 1, title: 1 }
},
{
$group:
{
_id: "Horror",
lastThreeMovies:
{
$lastN:
{
input: [ "$title", "$year" ],
n: 3
}
}
}
}
] )

前面的管道:

  • 使用 $match 过滤器将结果过滤为电影,其中 Horror 包含在 genres 数组中,并且 year 是一个整数。

  • 按 year 以升序对结果进行排序,然后按 title 以字母顺序进行排序作为平局破解条件。

  • 将所有结果文档分组为单一组。

  • 指定使用input : ["$title", "$year"]为$lastN输入的字段。

  • 使用 $lastN 返回针对 Horror 类型并且具有 n: 3 的最后三个文档(按年份升序排序,并以 title 作为平局打破者)。

可以使用 $lastN 累加器查找每个类别中的最后 n 个输入字段。

db.movies.aggregate( [
{
$match: { year: { $type: "int" } }
},
{
$unwind: "$genres"
},
{
$sort: { year: 1, title: 1 }
},
{
$group:
{
_id: "$genres",
movies:
{
$lastN:
{
input: [ "$title", "$year" ],
n: 3
}
}
}
},
{ $sort: { _id: 1 } },
{ $limit: 5 }
] )

前面的管道:

  • 使用 $match 过滤器 year 为整数的电影。

  • 使用 $unwind 在 genres 数组中针对每个流派创建单独的文档。

  • 按 year 升序排序结果,然后按 title 字母顺序排序。

  • 使用 $group 按 genres 对结果进行分组。

  • 使用 $lastN 返回每个具有 n: 3 类别的最后三个文档(按年份升序,以 title 作为决胜者)。

  • 指定使用input : ["$title", "$year"]为$lastN输入的字段。

  • 将输出限制为五份文档,以提高可读性。

您可以根据组密钥动态地赋值 n 的值。在此示例中,$cond 表达式使用 rated 字段更改 n 的值:

db.movies.aggregate( [
{
$match: {
rated: { $in: [ "G", "PG", "PG-13", "R" ] },
year: { $type: "int" },
title: { $regex: "^[A-Za-z0-9]" }
}
},
{ $sort: { title: 1 } },
{
$group:
{
_id: { rated: "$rated" },
movies:
{
$lastN:
{
input: "$title",
n: { $cond: { if: { $eq: ["$rated", "PG"] }, then: 3, else: 1 } }
}
}
}
},
{ $sort: { "_id.rated": 1 } }
] )

前面的管道:

  • 过滤器:用于过滤内容分级为 G、PG、PG-13 或 R 的电影,其中 year 是一个整数,并且 title 以字母数字字符开头。

  • 对结果按 title 进行字母顺序排序。

  • 按照 rated (内容评级) 将电影分组。

  • 使用 $cond 表达式,对于 PG 级别的电影,返回 3 部电影;对于所有其他级别,返回 1 部电影。

在输出中,PG 评级返回 3 部电影,而 G、PG-13 和 R 评级则各自返回 1 部电影。

给本页内容打分