'Mongodb c#driver - AggregateToCollectionOperation

I'm using the library MongoDB.Driver 2.8.1 (i'm planning to upgrade to the latest version, it's an old project).

I'm trying to use the operator $out for a query in my code so I wrote this piece of code (it's not wonderful, but it's not a problem)

await collectionAcc.Aggregate().AppendStage<BsonDocument>(@"{
                    $unwind: {
                        path: ""$Packs"",
                        preserveNullAndEmptyArrays: false
                    }
                }")
            .AppendStage<BsonDocument>(@"{
                    $replaceRoot: {
                                 newRoot: { $mergeObjects: [ ""$$ROOT"", {""Sku"" : ""$Packs.Sku"" }, {""SizePack"" : ""$Packs.Size"" } ] }
                            }
                }")
            .AppendStage<BsonDocument>(@"{ $out: ""accessoryPacks"" }").FirstOrDefaultAsync();

I run it and this error appear: "The pipeline for an AggregateOperation contains a $out operator. Use AggregateOutputToCollectionOperation instead"

Good, I try to use AggregateOutputToCollectionOperation class but I found no documentation at all, nor a decent example.

Someone can help me?



Solution 1:[1]

oh, I missed that you call FirstOrDefault. $out and $merge should be the last stages in pipeline, but FirstOrDefault additionally adds { limit : 1 } stage after them. You should add this stage inside pipeline before $out

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dododo