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") ]
 }]
相关推荐
ACP广源盛139246256731 小时前
Qwen3.8‑2.4T 开源落地@ACP#国产 MoE 大模型私有化部署中 MST 多屏转换芯片 GSV2231 硬件价值与应用场景
大数据·数据库·人工智能·嵌入式硬件
java_logo1 小时前
Docker 部署 openGauss:轻松搭建企业级开源关系型数据库平台
数据库·docker·开源·opengauss·轩辕镜像·opengauss部署教程·opengauss部署文档
旺仔学长 哈哈1 小时前
52486|高校专业评估不再靠表格:Spring Boot 本科专业质量评估管理系统实战
数据库·spring boot·毕业设计·教育管理
梦想的旅途22 小时前
企业微信Webhook回调怎么做自动回复和AI客服
数据库·机器人·自动化·企业微信·rpa
Zguigo2 小时前
OCR 核心原理 + 模型 + 检测与识别
数据库·ocr
凤山老林2 小时前
零停机数据库演进:Spring Boot 集成 Flyway 与平滑DDL变更策略
数据库·spring boot·后端
coder_lorraine2 小时前
手把手教你用 Docker Compose 部署 Twikoo 评论系统
mongodb·docker·容器
曹牧2 小时前
Oracle:取固定分隔符字符串中第一个元素
数据库·oracle
szarron2 小时前
VNA6 便携式矢量网络分析仪:从入门到精通
数据库·嵌入式硬件·测试工具·5g·射频工程
临床数据科学和人工智能兴趣组3 小时前
R语言中,列表是一种非常灵活的数据结构,它可以存储不同类型的对象,如向量、矩阵、数据框、甚至其他列表
数据结构·数据库·r语言·r语言-4.2.1·临床试验