Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading