Unofficial IAsyncEnumerable support for MongoDB C# Driver.
Provides ToAsyncEnumerable()
extensions for MongoDB IAsyncCursor
and IAsyncCursorSource
.
Asynchronous enumeration is implemeted so that the iterator fetches documents from database to memory one batch at time.
The size of the batch can be controller by BatchSize
property of e.g. AggregateOptions
or FindOptions
.
- Add MongoDB.Driver.Linq.AsyncEnumerable NuGet package to the project
- Include types in
MongoDB.Driver.Linq
namespace byusing MongoDB.Driver.Linq
- Call the
ToAsyncEnumerable()
extension for eitherIAsyncCursor
orIAsyncCursorSource
- Asynchronously iterate through elements returned by
ToAsyncEnumerable()
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
var client = new MongoClient();
var database = client.GetDatabase("ExampleDatabase");
var collection = database.GetCollection<BsonDocument>("ExampleCollection");
await foreach (var document in collection.Find(_ => true).ToAsyncEnumerable())
{
Console.WriteLine(document.ToString());
}
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
var client = new MongoClient();
var database = client.GetDatabase("ExampleDatabase");
var collection = database.GetCollection<BsonDocument>("ExampleCollection");
var options = new AggregateOptions { BatchSize = 1000 };
await foreach (var document in collection.Aggregate(options).ToAsyncEnumerable())
{
Console.WriteLine(document.ToString());
}