Mongo C# driver 2.0 - Find count without fetching documents

独自空忆成欢 提交于 2019-12-30 07:03:16

问题


A general count query will be doing a

int count = collection.Find(filter).Count();

Now that loads all the records as per the filter, so lets says I have 1 million records and out of those 0.5 million match my filter, so I'll have collection already filled with 0.5 documents. This is good enough if you want the documents, but what if you just want to know the count and not really need the documents, for memory sake.

Can I do something like this

int count = collection.Find(filter).SetLimit(1).Count();

This gives me the same count as the first expression, but I hope that the memory will not utilized as the first expression, help me to know the correct way to find the "count" without loading all documents. Thanks.


回答1:


You need to use the explicit CountAsync method and not Find:

long result = await collection.CountAsync(Builders<Hamster>.Filter.Eq(_ => _.Name, "bar"));


来源:https://stackoverflow.com/questions/32521835/mongo-c-sharp-driver-2-0-find-count-without-fetching-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!