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 ]
 }]
相关推荐
葫芦和十三7 小时前
图解 MongoDB 07|索引类型:七种索引,七种访问形状
后端·mongodb·agent
倔强的石头_1 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库
葫芦和十三1 天前
图解 MongoDB 06|模式演进:无 schema 是优势还是债
后端·mongodb·agent
葫芦和十三1 天前
图解 MongoDB 05|文档模型设计:内嵌 vs 引用,反范式不是免费午餐
后端·mongodb·agent
葫芦和十三2 天前
图解 MongoDB 03|CRUD 全链路:一条 find 怎么穿过 WiredTiger
后端·mongodb·agent
葫芦和十三2 天前
图解 MongoDB 04|索引模型:每建一个索引,就是在 B+-tree 森林里多栽一棵
后端·mongodb·agent
葫芦和十三3 天前
图解 MongoDB 02|BSON:你以为存的是 JSON,其实是带类型的二进制
后端·mongodb·agent
葫芦和十三3 天前
图解 MongoDB 01|文档数据库
后端·mongodb·agent
倔强的石头_4 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
冬奇Lab4 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm