Paging MongoDB query with C# drivers

gentiane picture gentiane · Dec 29, 2015 · Viewed 11.3k times · Source

I am using version 2.2 of MongoDB drivers for C#. I want to paginate a query : the response to the query must contain the items of the current page and the total count of items matching the query.

I want to do one query. With the mongo shell I can realize that as it :

var c = db.mycol.find({....}).skip(0).limit(10)
var total = c.count();
while (c.hasNext()) {
   print(tojson(c.next()));
}

But with the C# driver, I don't know how to do it with only one query.

var find = collection
  .Find(x => x.Valid == true)
  .Skip(0)
  .Limit(10);

var cursor = await find.ToCursorAsync(cancellationToken);
// How to get the count? There is no method in the IAsyncCursor interface.

Is it possible ? Some ideas ?

Answer

rnofenko picture rnofenko · Dec 30, 2015

You can't accomplish your task by sending to DB only one query. The common practice is following

var query = GetCollection().Find(x => x.Valid == true);
var totalTask = query.CountAsync();
var itemsTask = query.Skip(0).Limit(10).ToListAsync();
await Task.WhenAll(totalTask, itemsTask);
return new Page{ Total = totalTask.Result, Items = itemsTask.Result};