文章目录
$maxN
聚合运算符用于返回聚合分组中最大的n个元素,如果分组中的元素数量小于n,则返回分组的全部元素。
语法
{
$maxN:
{
input: <expression>,
n: <expression>
}
}
参数说明:
input
:指定输入表达式,表达式用于对分组中的每个元素计算后,$maxN
保留最大的n个值。n
:用于指定每个分组中要返回的成员数量,n
必须是正整数,可以是常量或者依赖于分组内的_id
值。
使用
空和缺失值的处理
$maxN
会过滤掉空值和缺失值
下面的聚合返回分组中最大的n
个文档:
db.aggregate( [
{
$documents: [
{
playerId: "PlayerA", gameId: "G1", score: 1 },
{
playerId: "PlayerB", gameId: "G1", score: 2 },
{
playerId: "PlayerC", gameId: "G1", score: 3 },
{
playerId: "PlayerD", gameId: "G1" },
{
playerId: "PlayerE", gameId: "G1", score: null }
]
},
{
$group:
{
_id: "$gameId",
maximumThreeScores:
{
$maxN:
{
input: "$score",
n: