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 ]
 }]
相关推荐
tiancaijiben12 小时前
阿里云SSL证书自动续签与部署完全指南:从托管服务到开源工具全方案解析
数据库
全堆鸿蒙12 小时前
25 数据库设计与表结构规划:5 张表的设计思路
数据库·华为·cocoa·harmonyos
笃行35012 小时前
【金仓数据库产品体验官】_坏得起_实测:备份恢复、PITR 时间穿越与主备切换——KingbaseES V9R3C18 深度体验(三)
数据库
笃行35014 小时前
从兼容到进阶:驱动直连、窗口函数与动态 SQL 实测——KingbaseES V9R3C18 深度体验(二)
数据库
笃行35014 小时前
MySQL 的 JSON 字段迁到金仓还能用吗?——KingbaseES V9R3C18 JSON 操作符与函数兼容实测
数据库
IpdataCloud15 小时前
跨境AI金融风险怎么防?IP风险画像的实战应用指南
数据库·tcp/ip·金融·ip
Alan_7517 小时前
API 接口慢调用根因定位:从 TCP 建连到数据库 IO 的全栈排查实战
数据库
多巴胺梦想家18 小时前
事务与并发控制:当多人同时操作数据库
服务器·数据库·oracle
howard200519 小时前
PostgreSQL起步
数据库·postgresql
书中枫叶19 小时前
从「上次几点喂奶」到全栈小程序:我做了个喂宝助手
mongodb·微信小程序·node.js