$slice operator not working as expected

Hello, I am new to this community.
I have been trying out to use $slice in my aggregation pipeline. Somehow it is not working as expected, the first index is not getting recognized.

The “dataArr” does resolves to an array (it is an array of Objects), and i am unsure why the $slice operator is not working.

Hello @Bojie_Xu, Welcome,

You can refer to the $slice documentation,

  • First argument is the array variable name that you passed correctly
  • Second argument is skip index number, which starts from 0, as you said the first index is not getting recognized so you have to pass 0 here.
  • Third argument is limit, number of elements return from an array after skip index.

Example:

{ key: [0,1,2,3,4,5,6,7,8,9,10] }

Query 1:

// Query 1:
{ key: { $slice: ["$key", 0, 5] } }
// Result
{ key: [0,1,2,3,4] }

Query 2:

// Query 2:
{ key: { $slice: ["$key", 5, 5] } }
// Result
{ key: [5,6,7,8,9] }

Hi @turivishal , thanks for your response!
I read the documentation, and expect data: {$slice: [“$dataArr”, 5, 10]} to return an array of 5 elements, but yet at stage 3 of my aggregation, the “data” variable is an array of 10 elements instead of 5.
I did try in stage 3 to use $slice on a normal array, testSlice: {$slice: [[1,2,3,4,5], 2, 3]}, and “testSlice” variable does return an array of 3 elements.

So im unsure why $slice does not work when im using in on the array i obtained from stage 2 of my aggregation pipeline and return me 10 elements instead of 5.

It looks you are confused between two $slice:

and

Hi @steevej , thanks for your reply.

I did look at the two, based on my understanding, one is used for aggregation() and the other for find() right? And in any case, i should expect an array of 5 elements instead of 10 when i apply $slice on “$dataArr” right?

Can you provide some explanation as to why line 6 of stage 3 of the aggregation pipeline produces an array of 10 elements when i use $slice: ["$dataArr, 5, 10] and should only give 5 elements.

Hello @Bojie_Xu,

Of course, it will give 10 elements if there are 10 elements from the 5th index because you have passed 10 in the third argument.
Can you check the total elements in dataArr using dataArrSize: { $size: "$dataArr"} in $project stage? As per your screenshot, the $group stage shows just 3 elements.

You can reproduce the issue in this playground also and share the link.

1 Like

Hello @turivishal ,

Thanks for your reply and clarification! I did not read the documents clearly and assumed the slicing works in a manner similar python :sweat_smile:
Thanks for your patience and help! Greatly appreciate it :slight_smile:

2 Likes