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 ]
 }]
相关推荐
Lethehong1 小时前
双擎并驱·全链路并行:KFS让TB级异构增量同步秒级到达
数据库
MC皮蛋侠客1 小时前
SQLAlchemy 系列(八):AsyncIO、并发与 Web 生命周期——让每个并发任务持有自己的 Session
数据库·python
一水2 小时前
Redis实战:一个AI工作流系统里的五个应用场景,从传参到限流的完整链路
数据库·redis·wpf
枫叶v.3 小时前
Prompt Injection 防不住怎么办?从 Source-Sink 模型设计 Agent 安全边界
数据库·安全·prompt
Lucky_Turtle3 小时前
【Milvus】向量数据库
数据库
吴声子夜歌3 小时前
MongoDB 8.0——安全性
数据库·mongodb
xcLeigh4 小时前
KingbaseES 的卢智能运维体架构深度拆解
运维·数据库·人工智能·ai·架构·ffmpeg·智能体
weixin_397574094 小时前
按行业定制分析视角
大数据·数据库·人工智能·企业数据治理·数据驱动决策·本体语义·企业经营分析
鹿角片ljp5 小时前
Redis 深度复习:从入门到面试通关
数据库·redis·面试
Ming_studying5 小时前
Python + SQLite FTS5 构建本地文档全文搜索器:增量索引、中文检索与高亮
jvm·数据库·python·sqlite