I am working with MongoDB for a long time and used $unionWith many times, but I didn’t know you can use $unionWith on the same collection you are doing the aggregation!
The only thing that is missing here is the option to iterate over in the next cycle once all the company products are fetched at least once.
So for example, let’s say I have 2 companies like this:
With you current solution, the whole aggregate will stop in the second iteration and it will return only 5 results (all five from the second company).
What I would like to happen is that the cycle would continue, where the second aggregate would also return 10 results (5 from second company and 5 from first company again).
Any idea how to add on top of your current answer that would cover that as well?
Btw, I am referencing your first solution with company data prefetched before the aggregation.
As I tried to said, this will not work since it will stop after the first cycle.
In your solution, the $limit is used on each $unionWith, so when we got to the last stage for global $limit and $skip, we will always have only the data from the first cycle to iterate.
In my example above, the second iteration will be the final, since it will not continue to iterate over the data because of the inner $limit in each $unionWith stage.