Please share the code you use without the $count stage.

Simply doing result = …aggregate( [ the pipeline without $count ] ) does not process all the documents of the result set so in fact you just get

Calling result.toArray() should get you all the documents.

Since you $unwind, just to count, you might want to simply $project the size of $ledgersData, which will not be blocking. And then $group to $sum of size of each array. This would at lease reduce the potential extra RAM usage of unwind.

And with a second look at the code, you could try a $count in the last $lookup pipeline. I am just not too sure of the empty array case.