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 ]
}]
相关推荐
rainFFrain3 小时前
(MySQL)库的操作
数据库·mysql
八股文领域大手子4 小时前
深入理解缓存淘汰策略:LRU 与 LFU 算法详解及 Java 实现
java·数据库·算法·缓存·mybatis·哈希算法
noravinsc4 小时前
django admin 中更新表数据 之后再将数据返回管理界面
数据库·django·sqlite
Bruce-li__6 小时前
DRF凭什么更高效?Django原生API与DRF框架开发对比解析
数据库·django·sqlite
noravinsc7 小时前
connection.cursor() 与 models.objects.filter
数据库·django·原生查询·orm查询
laimaxgg8 小时前
MySQL复合查询
数据库·mysql
编程在手天下我有9 小时前
Redis 常见问题深度剖析与全方位解决方案指南
数据库·redis·缓存·性能优化·数据持久化·分布式系统
辰哥单片机设计9 小时前
JQ6500语音模块详解(STM32)
数据库·mongodb
阿桨10 小时前
【保姆级教程-Centos7环境下部署mongodb并设置开机自启】
数据库·mongodb·centos
lolo大魔王10 小时前
MongoDB的增删改查操作
数据库·mongodb