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") ]
 }]
相关推荐
异常君12 分钟前
深入解析 InnoDB 死锁:从案例到方案,全流程透视指南
数据库·后端·mysql
꧁坚持很酷꧂14 分钟前
Qt实现文件传输服务器端(图文详解+代码详细注释)
开发语言·数据库·qt
苏牧keio34 分钟前
安装MySQL8.0
数据库
半糖土豆爱编码_35 分钟前
【mysql】Mac 通过 brew 安装 mysql 、启动以及密码设置
数据库·mysql·macos
Lary_Rock1 小时前
ubuntu20.04 Android14编译环境配置
大数据·数据库·elasticsearch
烂漫心空1 小时前
Windows 系统如何使用Redis 服务
数据库·数据仓库·redis·mysql·缓存·数据库架构
UniLCodes2 小时前
✅ MySQL 事务 & MVCC & ROLLBACK
数据库·mysql
SHIPKING3932 小时前
【LangChain核心组件】Memory:让大语言模型拥有持续对话记忆的工程实践
数据库·python·langchain·llm·memory
在努力的韩小豪2 小时前
MySQL中的UNION和UNION ALL【简单易懂】
数据库·sql·mysql·结果集合并·union和union all
SelectDB3 小时前
网易游戏 x Apache Doris:湖仓一体架构演进之路
大数据·数据库·数据分析