MongoDB.Driver 2.8.1中使用$out操作符报错,求助AggregateOutputToCollectionOperation的使用示例
解决MongoDB.Driver 2.8.1中$out操作符的报错问题
在MongoDB.Driver 2.8.x版本里,确实不能直接通过Aggregate().AppendStage()的方式添加$out阶段——因为这个版本的IAggregateFluent只支持纯查询类的聚合阶段,$out属于写操作,需要用专门的AggregateOutputToCollectionOperation类来处理,下面是具体的实现示例:
1. 构建聚合管道
先把你的聚合步骤整理成List<BsonDocument>(或者BsonArray),这样更清晰:
var pipeline = new List<BsonDocument> { // $unwind阶段 new BsonDocument("$unwind", new BsonDocument { { "path", "$Packs" }, { "preserveNullAndEmptyArrays", false } }), // $replaceRoot阶段 new BsonDocument("$replaceRoot", new BsonDocument { { "newRoot", new BsonDocument("$mergeObjects", new BsonArray { "$$ROOT", new BsonDocument("Sku", "$Packs.Sku"), new BsonDocument("SizePack", "$Packs.Size") }) } }) };
2. 创建并执行AggregateOutputToCollectionOperation
用AggregateOutputToCollectionOperation包装管道,指定目标集合名称,然后通过数据库实例执行:
// 创建输出操作实例,参数是源集合名称和管道 var outputOperation = new AggregateOutputToCollectionOperation<BsonDocument>(collectionAcc.CollectionNamespace.CollectionName, pipeline) { // 设置要输出的目标集合 OutputCollectionName = "accessoryPacks" }; // 执行操作 await collectionAcc.Database.RunOperationAsync(outputOperation);
关于升级到最新版本的提示
等你升级到最新版MongoDB.Driver后,就不用这么麻烦了——新版本已经支持直接在IAggregateFluent中使用$out,甚至提供了更简洁的Out()扩展方法:
await collectionAcc.Aggregate() .Unwind<BsonDocument>("$Packs", preserveNullAndEmptyArrays: false) .ReplaceRoot(new BsonDocument("$mergeObjects", new BsonArray { "$$ROOT", new BsonDocument("Sku", "$Packs.Sku"), new BsonDocument("SizePack", "$Packs.Size") })) .Out("accessoryPacks") .ExecuteAsync();
这样代码会更直观,和你最初写的逻辑更接近。
内容的提问来源于stack exchange,提问作者LucaFongaro
相关产品推荐
相关产品推荐

