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 小时前
【数据库系统原理】第19篇:计算机存储层次结构与数据库文件的物理组织
数据库·oracle
JAVA面经实录9177 小时前
操作系统面试题
java·服务器·数据库·计算机网络·面试
摇滚侠7 小时前
mariadb-libs 被 mysql-community-libs-5.7.28-1.el7.x86_64 取代
数据库·mysql·mariadb
DIY源码阁8 小时前
JavaSwing饮品管理系统 - MySQL版
java·数据库·mysql·eclipse
专注搞钱8 小时前
GPT-4o写设备Recipe:从3小时到10分钟
数据库·人工智能·gpt·半导体
东风破1379 小时前
达梦数据库实战:备份恢复与数据迁移全攻略(实例初始化、服务注册、路径迁移)
数据库·chrome
SelectDB技术团队9 小时前
2026 SelectDB AI 产品发布会:Agent Native 数据基础设施能力全景发布
数据库·人工智能·agent·apache doris·selectdb
爱吃羊的老虎9 小时前
【数据库】模块一:数据库基础与关系代数
数据库
dishugj10 小时前
iSCSI + Multipath + ASM:Oracle RAC 共享存储技术链详解
数据库·oracle
yoothey10 小时前
MySQL事务机制解析 - 面试高分知识点
数据库·mysql·面试