Getting an item count with MongoDB C# driver query builder

后端 未结 2 1301
眼角桃花
眼角桃花 2021-02-14 05:14

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.

相关标签:
2条回答
  • 2021-02-14 05:16

    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
    0 讨论(0)
  • 2021-02-14 05:35

    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);
    
    0 讨论(0)
提交回复
热议问题