C # mongodb driver 2.2.3 how to set batch format for cursor

I am using the official C # driver for MongoDB 2.2.3

How to set batch size for cursor using C # driver?

With javascript, I can create a cursor and set the batch size for it:

var cursor = db.statistics.find(query).batchSize(100)

and I can iterate over all elements using the following statement:

while(cursor.objsLeftInBatch()>0){
    var doc = cursor.next();
    //process doc
}

I would like to have the same behavior in C # with async / await support. I know that I can use the cursor from C #, but the default packet size is 4 MB. This is too much like returning to a client with a single call.

+4
source share
1 answer

You can set the batch size in the parameter FindOptions FindAsync.

:

var filter = new BsonDocument();
var options = new FindOptions<BsonDocument>
{
    // 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
    });
}
+4

All Articles