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") ]
 }]
相关推荐
夜雪闻竹11 小时前
Cursor 对话导入:解析 SQLite 里的宝藏
数据库·sqlite·ai编程
hhb_61811 小时前
PL/SQL核心技术难点梳理与实战应用案例解析
数据库·sql
m0_4708576412 小时前
PHP怎么实现工厂模式_Factory模式编写指南【指南】
jvm·数据库·python
用户4343092416912 小时前
Day29:图片上传 + 存数据库(Multer + MySQL)
数据库·后端
lolo大魔王13 小时前
MongoDB 索引机制详解:单字段索引、复合索引、唯一索引与性能优化
数据库·mongodb
newnazi13 小时前
RedHat10 安装MS SQL Server2025
linux·服务器·数据库
KaMeidebaby13 小时前
卡梅德生物技术快报|单 B 细胞抗体制备:流程优化、表达系统适配与性能数据
前端·数据库·其他·百度·新浪微博
2301_7838486513 小时前
mysql数据库迁移到云平台流程_使用数据传输服务DTS工具
jvm·数据库·python
爱喝水的鱼丶13 小时前
SAP-ABAP:ABAP函数 NUMBER_GET_NEXT 详解:从编号范围对象获取下一个编号
运维·数据库·学习·sap·abap
颖火虫盟主14 小时前
Claude Code Hook 系统详解与 Hello World 实操
前端·网络·数据库