MongoDB聚合运算符:$lastN 的数组操作

文章目录

$lastN聚合运算符针对数组返回数组的后n个元素

语法

js 复制代码
{ $lastN: { n: <expression>, input: <expression> } }
  • n为正整数表达式,指定要返回数组的后多少个元素
  • input 为一个数组表达式,返回其后n个元素

使用

  • $lastN返回数组元素的顺序与输入数组元素顺序保持一致
  • $lastN不会过滤掉输入数组中的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 ]}
])

下面的聚合使用$lastN操作符取出每个运动员的三个最低分,会使用$addFields将得分放在一个新字段lastScores中:

js 复制代码
db.games.aggregate([
   { $addFields: { lastScores: { $lastN: { n: 3, input: "$score" } } } }
])

操作返回的结果如下:

json 复制代码
[{
  "playerId": 1,
  "score": [ 1, 2, 3 ],
  "lastScores": [ 1, 2, 3 ]
},
{
  "playerId": 2,
  "score": [ 12, 90, 7, 89, 8 ],
  "lastScores": [ 7, 89, 8 ]
},
{
  "playerId": 3,
  "score": [ null ],
  "lastScores": [ null ]
},
{
  "playerId": 4,
  "score": [ ],
  "lastScores": [ ]
},
{
  "playerId": 5,
  "score": [ 1293, null, 3489, 9 ],
  "lastScores": [ null, 3489, 9 ]
},
{
  "playerId": 6,
  "score": [ "12.1", 2, NumberLong("2090845886852"), 23 ],
  "lastScores": [ 2, NumberLong("2090845886852"), 23 ]
 }]
相关推荐
正在走向自律4 分钟前
金仓数据库KingbaseES基础语法详解与实践指南
数据库·国产数据库·ddl·dml·kingbasees·sql语法·电科金仓
alonewolf_995 分钟前
MySQL全局优化详解与8.0新特性全面解读
数据库·mysql
ASS-ASH7 分钟前
快速处理虚拟机磁盘扩容问题
linux·数据库·vmware·虚拟机·磁盘扩容
爱写bug的野原新之助13 分钟前
数据库及navicat工具
数据库·网络爬虫·工具
数据知道16 分钟前
一文掌握 MongoDB 存储引擎 WiredTiger 的原理
数据库·mongodb·数据库架构
Full Stack Developme21 分钟前
Mycat 2 实现 MySQL 读写分离,并且实现 主从同步
android·数据库·mysql
我是人✓24 分钟前
Spring IOC入门
java·数据库·spring
Hello.Reader25 分钟前
PyFlink DataStream 程序骨架、常用 Source/Sink、状态(State)、与 Table/SQL 互转一篇搞定
数据库·sql·linq
三不原则32 分钟前
故障案例:模型推理响应慢,排查 Redis 缓存集群问题
数据库·redis·缓存
alonewolf_9937 分钟前
MySQL Explain详解与索引优化实战
数据库·mysql·adb