MongoDB聚合运算符:$maxN(用于数组)

文章目录

$maxN聚合运算符返回数组中最大的n个值。

语法

{ $maxN: { n: <expression>, input: <expression> } }

参数说明:

  • n:正整数表达式,用于指定返回数组元素的数量。
  • input:可以解析为数组的表达式。

使用

  • n不能小于1
  • $maxN忽略数组中的null值
  • 如果n大于等于input数组元素数量,返回input数组中所有的元素
  • 如果input解析为非数组的值,聚合操作将报错
  • 如果input数组元素中同时包含数值和字符串元素,则根据BSON比较规则,字符串将排在数组前面

举例

使用下面的脚本创建scores集合:

db.scores.insertMany([
    { "playerId" : 1, "score" : [ 1, 2, 3 ] },
    { "playerId" : 2, "score" : [ 12, 90, 7, 89, 8 ] },
    { "playerId" : 3, "score" : [ null ] },
    { "playerId" : 4, "score" : [ ] }
    { "playerId" : 5, "score" : [ 1293, "2", 3489, 9 ]}
])

下面的聚合操作使用$maxN运算符检索得分最高的两个玩家,并使用$addFields阶段将得分最高的放到一个新字段maxScores

db.scores.aggregate([
   { $addFields: { maxScores: { $maxN: { n: 2, input: "$score" } } } }
])

操作返回下面的结果:

[{
  "playerId": 1,
  "score": [ 1, 2, 3 ],
  "maxScores": [ 3, 2 ]
},
{
  "playerId": 2,
  "score": [ 12, 90, 7, 89, 8 ],
  "maxScores": [ 90, 89 ]
},
{
  "playerId": 3,
  "score": [ null ],
  "maxScores": [ ]
},
{
  "playerId": 4,
  "score": [ ],
  "maxScores": [ ]
},
{
  "playerId": 5,
  "score": [ 1293, "2", 3489, 9 ],
  "maxScores": [ "2", 3489 ]
}]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值