简体   繁体   中英

MongoDB C# Driver - CountDocuments erronously returns wrong value

Ok, so this is a bit tricky.

I have this block

        var collResult = _coll.Find(cnFilter & statusFilter & startFilter & endFilter & textFilter);
        var findTask = Task.Factory.StartNew(() => {
            return collResult.SortByDescending(i => i.dim_InvoiceDate_key).Skip(skip).Limit(take);
        });
        var countTask = Task.Factory.StartNew(() => {
            return collResult.CountDocuments();
        });
        await Task.WhenAll(findTask, countTask);

the CountDocuments most of the time returns an accurate number representing the filtered query without Skip and Limit. But occasionally, when it has to count in excess of 25k or so, it returns the same count as the findTask result contains. (50 in most cases)

Trying to use the old _coll.Count() and I get obsolete errors thrown at me, is there anything I can do for this?

It seems though that if the findTask finishes before Count even gets time to start (due to concurrency or whatever), the Limit set inside findTask is leaking through the shared Find() and CountDocuments() is then thinking its supposed to count that. It wasnt even enough that I put the task before the findTask so that it should have a sporting chance to finish before, I had to create it's own Find-pipeline so that it didnt leak over.

            var findResult = _coll.Find(cnFilter & orderDateFilter & deliveryDateFilter & statusFilter & keywordFilter);
            var countResult = _coll.Find(cnFilter & orderDateFilter & deliveryDateFilter & statusFilter & keywordFilter).CountDocumentsAsync();

and then I use the countResult task seperately

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM