Limit the items returned from array

I have my collection where every document has an array of item. But some documents has more than 10k items in their array.

What Im trying to do is to select the document and limit the number of displayed items from that array in 50 for example (to speed up the query, because it takes so long to load all the items).

I dont know if thats possible…
I was trying:

const game = await Game.findOne({name}, {"lastRefreshed": 0, "createdAt": 0, "tokens": { $slice: 25 }}).lean().exec();

The tokens array has more than 10k items, and the code above does not work.

Hello @foco_radiante,

The syntax to restrict the number of elements returned from an array field using $slice in the projection ("tokens": { $slice: 25 }) is correct - and I believe it works. I cannot tell further if there is an issue from the available details in your question.

See the usage from the manual:

The syntax findOne(…).lean().exec(), as I do not recognize it, makes me think that you might be using an obstruction abstraction layer like mongoose.

If it is the case it might be a good idea to add mongoose in the tag list so that people only tracking mongoose related topics see your post.

How does it behave exactly? Errors or wrong results?

I am not sure you can have projection with exclusion like lastRefreshed:0 and inclusion like the tokens specification. As mentioned by @Prasad_Saya, $slice should work. I would try just using the $slice part. In principal, all other fields will be excluded.