使用C#驱动程序分页MongoDB查询

gen*_*ane 8 c# mongodb mongodb-csharp-2.0 mongodb-.net-driver

我使用的是用于C#的2.2版MongoDB驱动程序.我想对查询进行分页:对查询的响应必须包含当前页面的项目以及与查询匹配的项目总数.

我想做一个查询.使用mongo shell我可以意识到:

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

但是使用C#驱动程序,我不知道如何只使用一个查询.

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.
Run Code Online (Sandbox Code Playgroud)

可能吗 ?一些想法?

rno*_*nko 9

您只能通过向DB发送一个查询来完成任务.通常的做法是遵循

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};
Run Code Online (Sandbox Code Playgroud)