Search code examples
c#mongodbaggregatemongodb-.net-driverfluent

MongoDB Fluent Aggregate Conditional Stages


When using the Fluent aggregation interface, why doesn't the stages added later not work (stage 3)?

var fluentPipeline = _userToGroup.Aggregate()
            .AppendStage<BsonDocument>("stage 1")
            .AppendStage<BsonDocument>("stage 2");
if (condition)
    fluentPipeline.AppendStage<BsonDocument>("stage 3");
fluentPipeline.ToListAsync();

Stage 3 works when added to the pipeline in the same code line like below. Which means it is not a problem with the stage but how the stage is added to the pipeline as I understand it. The question is why?

var fluentPipeline = _userToGroup.Aggregate()
            .AppendStage<BsonDocument>("stage 1")
            .AppendStage<BsonDocument>("stage 2")
            .AppendStage<BsonDocument>("stage 3");

Solution

  • You can open github to preview the body of the AppendStage method.

    It turns out that there's a return statement so it always returns a new PipelineDefinition instead of modifying the existing one. Therefore you have to assign this returned value to a variable. Try:

    var fluentPipeline = _userToGroup.Aggregate()
                .AppendStage<BsonDocument>("stage 1")
                .AppendStage<BsonDocument>("stage 2");
    
    if (condition)
        fluentPipeline = fluentPipeline.AppendStage<BsonDocument>("stage 3");
    
    fluentPipeline.ToListAsync();