如何使用 Mongo 聚合框架从起始索引开始切片数组?

问题描述 投票:0回答:1

使用 mongo 聚合框架,如何在不知道数组长度的情况下从起始索引 2 开始对数组进行切片?

在 javascript 中,你可以通过以下方式实现:

const array = [1, 2, 3, 4, 5, 6]
array.slice(2)
> [ 3, 4, 5, 6 ]

我尝试使用 mongo

$slice
运算符执行以下操作,但它返回数组中的前 2 个元素,而不是返回从索引 2 开始的所有项目。

db.collection.aggregate([
  { $project: { _id: 1, array: { $slice: ['$array', 2] } } }
])
mongodb aggregation-framework
1个回答
3
投票

使用数组的大小:

db.collection.aggregate([
  { $project: { _id: 1, array: { $slice: ['$array', 2, { $size: '$array' }] } } }
]);

查看它在 playground 示例中的工作原理

© www.soinside.com 2019 - 2024. All rights reserved.