Getting an item count with MongoDB C# driver query builder

强颜欢笑 提交于 2019-12-21 04:04:09

问题


Using the c# driver for MongoDB I can easily construct a query against which I can then add SetSkip() and SetLimit() parameters to constrict the result set to a certain size.

However I'd like to be able to know what item count of the query would be before applying Skip and Take without executing the query and loading the entire result set (which could be huge) into memory.

It looks like I can do this with MongoDB directly through the shell by using the count() command. e.g.:

 db.item.find( { "FieldToMatch" : "ValueToMatch" } ).count()

Which just returns an integer and that's exactly what I want. But I can't see a way in the documentation of doing this through the C# driver. Is it possible?

(It should be noted that we're already using the query builder extensively, so ideally I'd much rather do this through the query builder than start issuing commands down to the shell through the driver, if that's possible. But if that's the only solution then an example would be helpful, thanks.)

Cheers, Matt


回答1:


You can do it like this:

var server = MongoServer.Create("mongodb://localhost:27020");
var database = server.GetDatabase("someDb");

var collection = database.GetCollection<Type>("item");
var cursor = collection.Find(Query.EQ("FieldToMatch" : "ValueToMatch"));

var count = cursor.Count(); 

Some notes:

  1. You should have only one instance of server (singleton)
  2. latest driver version actually returns long count instead of int
  3. Cursor only fetches data once you iterate
  4. You can configure a lot of things like skip, take, specify fields to return in cursor before actually load data (start iteration)
  5. Count() method of cursor loads only document count



回答2:


I'm using the Driver 2.3.0 and now is also possible to do that like this:

...
IMongoCollection<entity> Collection = db.GetCollection<entity>(CollectionName);
var yourFilter = Builders<entity>.Filter.Where(o => o.prop == value);
long countResut = Collection.Count(yourFilter);


来源:https://stackoverflow.com/questions/9314886/getting-an-item-count-with-mongodb-c-sharp-driver-query-builder

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