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 ]
 }]
相关推荐
2301_790300969 分钟前
用Python读取和处理NASA公开API数据
jvm·数据库·python
万象.21 分钟前
redis持久化:AOF和RDB
数据库·redis·缓存
tod1131 小时前
力扣高频 SQL 50 题阶段总结(四)
开发语言·数据库·sql·算法·leetcode
!chen1 小时前
Redis快速实现布隆过滤器
数据库·redis·缓存
2301_790300961 小时前
数据分析与科学计算
jvm·数据库·python
-XWB-1 小时前
【Oracle】Oracle诊断系列(2/6):锁问题与阻塞分析——解决“卡住”的会话
数据库·oracle
cqsztech2 小时前
Oracle 26ai 2节点RAC 保姆级搭建步骤
数据库·oracle
TDengine (老段)2 小时前
金融风控系统中的实时数据库技术实践
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
看我干嘛!2 小时前
第三次python作业
服务器·数据库·python
2501_936960362 小时前
ROS快速入门教程
数据库·mongodb