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") ]
 }]
相关推荐
setmoon2141 分钟前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_8331977331 分钟前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
执笔画情ora44 分钟前
oracle数据库优化-表碎片优化性能。
数据库·oracle
givemeacar1 小时前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis
skiy1 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
IvorySQL1 小时前
PostgreSQL 技术日报 (3月24日)|当 MVCC 成本被重新审视
数据库·postgresql·开源
2401_895521341 小时前
PostgreSQL_安装部署
数据库·postgresql
Hvitur1 小时前
软考架构师【第六章】数据库设计基础知识
数据库·oracle
养生技术人1 小时前
Oracle OCP认证考试题目详解082系列第5题
运维·数据库·sql·oracle·开闭原则
2401_879693871 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python