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

文章目录

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

语法

js 复制代码
{ $maxN: { n: <expression>, input: <expression> } }

参数说明:

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

使用

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

举例

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

js 复制代码
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

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

操作返回下面的结果:

json 复制代码
[{
  "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 ]
}]
相关推荐
m0_734949796 小时前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
m0_514520576 小时前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
NaMM CHIN6 小时前
sql实战解析-sum()over(partition by xx order by xx)
数据库·sql
不瘦80斤不改名6 小时前
深入浅出 MySQL(一):一文理清 SQL 核心规范与五大分类
数据库·sql·mysql
woniu_buhui_fei7 小时前
MySQL知识整理二
数据库·mysql
Polar__Star7 小时前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
Lucifer三思而后行8 小时前
zCloud 中 Oracle 实例状态未知问题记录
数据库·oracle
island13148 小时前
最详细VMware Workstation 17 上安装 Ubuntu 系统
linux·数据库·ubuntu
卢傢蕊8 小时前
MongoDB
数据库·mongodb
m0_743623928 小时前
React 自定义 Hook 的命名规范与调用规则详解
jvm·数据库·python