Home > Back-end >  Does the MongoDB C# driver buffer multiple documents with ForEachAsync?
Does the MongoDB C# driver buffer multiple documents with ForEachAsync?

Time:03-20

When querying a large collection of documents, you don't want to fill up memory. Using the MongoDB C# driver, I read that this is where ForEachAsync comes in handy. I have lots of little documents though. So my question is

Does ForEachAsync (1) make a round trip to the DB for every document OR (2) buffer documents in batches and iterate on those as they come in?

Seems like scenario 1 would cause lots of waiting around for the request/response and also more strain on the DB. My guess is it is implemented as 2, but then what's the worst case memory usage? Does the driver set some kind of memory limit on the buffer?

CodePudding user response:

ForEachAsync as a lot of other similar methods is just a wrapper over mongodb cursor which works via batches. You can configure this behavior via BatchSize option for example in AggregateOptions here.

  • Related