MongoDB聚合运算符:$firstN 的数组操作

文章目录

$firstN聚合运算符针对数组返回数组的前n个元素

语法

js 复制代码
{ $firstN: { n: <expression>, input: <expression> } }
  • n为正整数表达式,指定要返回数组的前多少个元素
  • input 为一个数组表达式,返回其前n个元素

使用

  • $firstN返回数组元素的顺序与输入数组元素顺序保持一致
  • $firstN不会过滤掉输入数组中的null值元素
  • 如果n大于等于输入数组元素的数量,则返回整个数组
  • 如果input被解析为空数组,聚合操作将报错

举例

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

js 复制代码
db.games.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, null, 3489, 9 ]},
    { "playerId" : 6, "score" : [ "12.1", 2, NumberLong("2090845886852"), 23 ]}
])

下面的聚合使用$firstN操作符取出每个运动员的三个最高分,会使用$addFields将得分放在一个新字段firstScores中:

js 复制代码
db.games.aggregate([
   { $addFields: { firstScores: { $firstN: { n: 3, input: "$score" } } } }
])

操作返回的结果如下:

json 复制代码
[{
  "playerId": 1,
  "score": [ 1, 2, 3 ],
  "firstScores": [ 1, 2, 3 ]
},
{
  "playerId": 2,
  "score": [ 12, 90, 7, 89, 8 ],
  "firstScores": [ 12, 90, 7 ]
},
{
  "playerId": 3,
  "score": [ null ],
  "firstScores": [ null ]
},
{
  "playerId": 4,
  "score": [ ],
  "firstScores": [ ]
},
{
  "playerId": 5,
  "score": [ 1293, null, 3489, 9 ],
  "firstScores": [ 1293, null, 3489 ]
},
{
  "playerId": 6,
  "score": [ "12.1", 2, NumberLong("2090845886852"), 23 ],
  "firstScores": [ "12.1", 2, NumberLong("2090845886852") ]
 }]
相关推荐
观远数据6 分钟前
决策闭环的第三公里:从洞察到行动之间,AI能补上什么
大数据·数据库·人工智能
满昕欢喜37 分钟前
2.4 本地服务器组和中央管理服务器
数据库·sqlserver
空堂与归1 小时前
Python 操作 MySQL 与 Redis:AI 应用的数据读写双引擎
数据库
2401_873479401 小时前
IPv6查出来的地理位置是错的?用双栈IP库解决定位偏差问题
网络·数据库·tcp/ip·ip
CNSSIRD数据库1 小时前
中国创新型中小企业研究数据库2022-2026
大数据·数据库·数据分析·论文笔记
2601_963282771 小时前
极寒区域无线通信系统工程实战:黑龙江冰雪环境对讲机组网、射频损耗与设备耐寒可靠性优化全指南
大数据·数据库·人工智能
小王同学66662 小时前
Django 5 中实现文件上传功能
数据库·django·sqlite
zuozewei3 小时前
《GB/T 47241-2026 - 虚拟电厂技术导则》国标解析.md
数据库
小张同学a.4 小时前
LAMP架构4——MySQL高可用
linux·运维·服务器·数据库·mysql·架构·负载均衡
Xxtaoaooo13 小时前
工业 IoT 存储引擎选型:多模引擎在数据模型与存储设计上的取舍
数据库·物联网·dolphindb