C# Driver Materialized View - Iteration Required?

I have a materialized view aggregation query (last stage is $merge into another collection) which works well. I don’t actually need the call to AggregateAsync() to return the results as all I care about is that it updates the collection. Do I need to iterate over the resulting cursor to ensure that all updates occur or can I just ignore the returned cursor?

Right now I have the following which seems unnecessary but I’m not sure how to prove that it is necessary without setting up a query that guarantees it will update/return more than some batch size that I don’t explicitly set:

using(var cursor = await collection.AggregateAsync(pipeline, options))
{
  while (await cursor.MoveNextAsync())
  {
    // doing nothing here...
  }
}

Is the while loop necessary or has the database already processed the full update prior to returning any results?

Hi Thomas, thank you for your good question.
Your understanding is correct, after the collection.AggregateAsync method is executed, the pipeline is already executed on the server, and the last merge state is executed as well. Therefore the reading of the pipeline results will not affect the database updates, and can be skipped in this case.

Thanks! For one additional point of clarification to make sure that resources are properly cleaned up… Do I still need a using statement here or is it safe to simply have await collection.AggregateAsync(pipeline, options)); on a line?

Yes, in case of AggregateAsync method the result cursor needs to be disposed. More suitable method in this case would be collection.AggregateToCollection or collection.AggregateToCollectionAsync.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.