Search code examples
mongodbaggregation-framework

How to Slice Array From Starting Index with the Mongo Aggregate Framework?


Using the mongo aggregation framework, how can I slice an array from a starting index of 2 without knowing the length of the array?

In javascript, you can achieve that by doing:

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

I tried doing the following with mongo $slice operator but it returns the first 2 elements in the array instead of returning all the items starting from index 2.

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

Solution

  • Use the size of the array:

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

    See how it works on the playground example