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") ]
 }]
相关推荐
薛定谔的算法3 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend4 小时前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术5 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
似水流年流不尽思念9 小时前
MongoDB 有哪些索引?适用场景?
后端·mongodb
Raymond运维10 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉10 小时前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger1 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化