MongoDB return embedded document in array of arrays

Solution for MongoDB return embedded document in array of arrays
is Given Below:

I am learning the MongoDB aggregation framework and I’m struggling with this particular query to return subdocuments as arrays within an array;

My schema is something like this

board: {
_id: ObjectId,
name: 'general',
prefix: 'gen',
threads: [ObjectId, ObjectId, ObjectId]
}


thread: {
_id: ObjectId,
title: 'some title',
body: 'some content',
creator: {
  _ref: ObjectId
},
board: {
  _ref: ObjectId,
  name: 'general',
  prefix: 'gen'
},
createdAt: 'time string',
updatedAt: 'time string',
posts: [ObjectId, ObjectId, ObjectId]
}


post: {
_id: ObjectId,
thread: ObjectId,
body: 'some post content',
createdAt: 'time string',
updatedAt: 'time string',
creator: {
  _ref: ObjectId
}
}

(don’t worry about how it looks. it’s designed very specifically and I left out a lot of unnecessary fields and also included some to give a more simplified overview)

Each board can have many many different threads. I am trying to create sort of a customized pagination. I want to return the boards object, where the threads field is an array of threads of a maximum size. so for example if I had 108 threads in this board, it would return 11 arrays inside threads. the first 10 have 10 threads each, the last has 8. I also want the threads inside each array to be populated with their corresponding document. That’s not the issue for me. it’s creating the actual arrays.

note: the threads field is NOT an unbounded array. it has a maximum size that is unknown at the moment.

I CANNOT use the ObjectId to create the arrays. I have read solutions which take advantage of the fact that ObjectId includes creation data and more, and it was a good solution, however – I cannot use it for my implementation. I have many different types of sorting options and the createdAt and updatedAt fields are manipulated sparsely to aid in some additional sorting after the fact.. anyway this is no concern, I simply wanted to state that I am aware of this solution, but I cannot use it.

I have tried so many different solutions, none of which worked. I would really like to do this during the query and not in javascript if possible. If it’s not possible inside the query, what would be the best solution to achieve the desired result in javascript? I am using a nested loop at the moment and I would really like to avoid this but I am unsure of how to.