Getting an item count with MongoDB C# driver query builder

后端 未结 2 1295
眼角桃花
眼角桃花 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("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

提交回复
热议问题