能否将MongoDB aggregate查询存入变量后传入AggregateFluent调用
问题解答
完全可以实现你的需求,MongoDB .NET 驱动的 Aggregate 方法原生支持传入预定义的聚合管道参数,以下是两种常用的实现方式:
方式1:手动构建Bson格式管道数组
直接通过官方提供的BsonDocument类拼接和你的查询逻辑完全对应的管道,存入变量后直接传入调用即可:
using MongoDB.Bson; using MongoDB.Driver; // 定义聚合管道变量 var aggregatePipeline = new BsonDocument[] { new BsonDocument("$facet", new BsonDocument { { "home", new BsonArray { new BsonDocument("$match", new BsonDocument("$expr", new BsonDocument("$eq", new BsonArray { "$IsHomePage", true }))) } }, { "notHome", new BsonArray { new BsonDocument("$match", new BsonDocument("$expr", new BsonDocument("$and", new BsonArray { new BsonDocument("$ne", new BsonArray { "$IsHomePage", true }), new BsonDocument("$eq", new BsonArray { "$IsTagged", true }) }))), new BsonDocument("$sample", new BsonDocument("size", 50)) } } }), new BsonDocument("$project", new BsonDocument("union", new BsonDocument("$concatArrays", new BsonArray { "$home", "$notHome" }))), new BsonDocument("$unwind", new BsonDocument("path", "$union")), new BsonDocument("$replaceRoot", new BsonDocument("newRoot", "$union")) }; // 调用时直接传入变量即可 return await db.posts.Aggregate<Post>(aggregatePipeline).ToListAsync();
方式2:JSON管道反序列化
如果你已经写好了JSON格式的聚合语句,不需要手动转成BsonDocument,直接反序列化即可生成可用的管道变量:
using MongoDB.Bson; using MongoDB.Bson.Serialization; // 你原始的聚合管道JSON字符串 string pipelineJson = @" [ {""$facet"": { ""home"": [{""$match"": {""$expr"": {""$eq"": [""$IsHomePage"", true]}}}] , ""notHome"": [ {""$match"": {""$expr"": {""$and"": [{""$ne"": [""$IsHomePage"", true]}, {""$eq"": [""$IsTagged"", true]}]}}} , {""$sample"": {""size"": 50}} ] }}, {""$project"": {""union"": {""$concatArrays"": [""$home"", ""$notHome""]}}}, {""$unwind"": {""path"": ""$union""}}, {""$replaceRoot"": {""newRoot"": ""$union""}} ]"; // 反序列化为Bson管道数组 var aggregatePipeline = BsonSerializer.Deserialize<BsonDocument[]>(pipelineJson); // 调用方式和上面完全一致 return await db.posts.Aggregate<Post>(aggregatePipeline).ToListAsync();
注意事项:需要确保你定义的
Post实体类的字段属性和聚合返回的文档结构匹配,否则会出现反序列化失败的问题。
内容的提问来源于stack exchange,提问作者user1765862
相关产品推荐
相关产品推荐

