我正在使用MongoDB 2.2.3的官方C#驱动程序
如何使用C#驱动程序为光标设置批量大小?
使用Javascript我可以创建一个游标并为其设置批量大小:
var cursor = db.statistics.find(query).batchSize(100)
我可以使用以下语句遍历所有项目:
while(cursor.objsLeftInBatch()>0){ var doc = cursor.next(); //process doc }
我想在C#中使用async/await支持具有相同的行为.我知道我可以使用C#中的游标,但它的默认批量大小是4MB.这太匹配了,无法通过一次调用返回客户端.
您可以在FindOptions
参数中设置批量大小FindAsync
.
以下是显式处理批次的基本模式:
var filter = new BsonDocument(); var optiOns= new FindOptions{ // Get 100 docs at a time BatchSize = 100 }; using (var cursor = await test.FindAsync(filter, options)) { // Move to the next batch of docs while (await cursor.MoveNextAsync()) { var batch = cursor.Current; foreach (var doc in batch) { // process doc } } }
但您也可以调用ForEachAsync
光标,批量将按需透明地获取:
using (var cursor = await test.FindAsync(filter, options)) { await cursor.ForEachAsync(doc => { // process doc }); }