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 ]
}]
相关推荐
ChinaRainbowSea9 分钟前
7. LangChain4j + 记忆缓存详细说明
java·数据库·redis·后端·缓存·langchain·ai编程
小马学嵌入式~1 小时前
嵌入式 SQLite 数据库开发笔记
linux·c语言·数据库·笔记·sql·学习·sqlite
Java小白程序员2 小时前
MyBatis基础到高级实践:全方位指南(中)
数据库·mybatis
Monly212 小时前
人大金仓:merge sql error, dbType null, druid-1.2.20
数据库·sql
不宕机的小马达2 小时前
【Mysql|第一篇】Mysql的安装与卸载、Navicat工具的使用
数据库·mysql
float_六七2 小时前
数据库连接池:性能优化的秘密武器
数据库·oracle·性能优化
码界奇点2 小时前
MongoDB vs MySQLNoSQL与SQL数据库的架构差异与选型指南
数据库·sql·mongodb·系统架构
IT 小阿姨(数据库)2 小时前
PgSQL中pg_stat_user_tables 和 pg_stat_user_objects参数详解
linux·运维·数据库·sql·postgresql·oracle
倔强的石头_2 小时前
Windows系统下KingbaseES数据库保姆级安装教程(附常见问题解决)
数据库
麦兜*3 小时前
MongoDB 常见错误解决方案:从连接失败到主从同步问题
java·数据库·spring boot·redis·mongodb·容器