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") ]
 }]
相关推荐
灯澜忆梦1 分钟前
【MySQL11】进阶篇 | 索引_#3使用规则
数据库·sql·mysql·性能优化
名字还没想好☜6 分钟前
Go 的 sync.Cond 实战:用条件变量做等待/通知,比忙轮询省 CPU
开发语言·数据库·后端·golang·go
wWYy.42 分钟前
Mysql:有哪些锁?
数据库·mysql
李可以量化43 分钟前
Tornado 从了解到精通(一)下:异步与非阻塞 IO 核心原理
java·数据库·tornado
VALENIAN瓦伦尼安教学设备1 小时前
ASHOOTER激光对中仪如何通过颜色确定调整是否合适
数据库·嵌入式硬件·算法
Wang's Blog1 小时前
AI Agent白手起家58: 项目可观测性——用 LangSmith 实现全链路追踪
数据库·人工智能
SL_staff2 小时前
JVS数字底座实践:如何复用企业文档能力快速构建知识类应用
java·数据库·程序员
qq_185198692 小时前
SpingBoot3入门学习-Web开发-三
java·数据库·学习
农村小镇哥3 小时前
C#读取CSV文件的方法
服务器·数据库·c#
IMPYLH3 小时前
HTML 的 <embed> 元素
前端·数据库·html