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 ]
}]

相关推荐

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

    2024-04-05 09:00:01       31 阅读
  2. MongoDB聚合运算符:$maxN

    2024-04-05 09:00:01       26 阅读
  3. MongoDB聚合运算符:$max

    2024-04-05 09:00:01       39 阅读
  4. MongoDB聚合运算符:$add

    2024-04-05 09:00:01       55 阅读
  5. MongoDB聚合运算符:$arrayToObject

    2024-04-05 09:00:01       53 阅读
  6. MongoDB聚合运算符;$dateToParts

    2024-04-05 09:00:01       53 阅读
  7. MongoDB聚合运算符:$dayOfWeek

    2024-04-05 09:00:01       55 阅读
  8. MongoDB聚合运算符:$dayOfMonth

    2024-04-05 09:00:01       52 阅读
  9. MongoDB聚合运算符;$dateToString

    2024-04-05 09:00:01       48 阅读
  10. MongoDB聚合运算符:$dayOfYear

    2024-04-05 09:00:01       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-05 09:00:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-05 09:00:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-05 09:00:01       87 阅读
  4. Python语言-面向对象

    2024-04-05 09:00:01       96 阅读

热门阅读

  1. LeetCode-热题100:55. 跳跃游戏

    2024-04-05 09:00:01       35 阅读
  2. redis分布式锁

    2024-04-05 09:00:01       28 阅读
  3. 什么是CSS编程语言?怎么使用?

    2024-04-05 09:00:01       37 阅读
  4. 【leetcode面试经典150题】9.跳跃游戏(C++)

    2024-04-05 09:00:01       34 阅读
  5. tomcat 常用的一些配置

    2024-04-05 09:00:01       27 阅读
  6. jvm的垃圾回收策略

    2024-04-05 09:00:01       38 阅读
  7. Linux服务器之间SSH免密登陆

    2024-04-05 09:00:01       40 阅读
  8. ssh 连接linux经常断开

    2024-04-05 09:00:01       31 阅读