Stream a large response from MongoDB using NET 6 AsyncEnumerable?

115 Views Asked by At

I was hoping I could use IAsyncEnumerable to stream a response from MongoDB and not have the memory of my API-App eaten up.

I am fetching from MongoDB like this to get an IAsyncEnumerable

public async IAsyncEnumerable<Record> GetAllRecords()
{
    var collection = GetCollection<Record>();
    var cursor = await collection.FindAsync(FilterDefinition<Record>.Empty);
    while (await cursor.MoveNextAsync())
    {
        foreach (var current in cursor.Current)
            yield return current;
    }
}

And then just returning that IAsyncEnumerable from my Controller.

But alas my application is eating up memory while sending out all the records. Am I doing this wrong, or are my NET6 AsyncEnumerable hopes to high?

0

There are 0 best solutions below