我正在尝试使用C#驱动程序创建一个mongodb聚合管道,其中包括redact,后跟项目。我尝试了下面显示的几种方法,但在每种情况下只执行管道的第一阶段。 AppendStage似乎没有附加到下一个阶段。那么如何使用C#mongodb驱动程序进行redact后跟一个项目。请注意,流畅的界面不直接支持编辑,但另一篇帖子显示使用下面的代码来完成第一阶段。
我正在使用2.4.3版本的C#驱动程序和mongodb版本3.4.4
string redactJson = System.IO.File.ReadAllText(@"redactTest.json");
string projectJson = System.IO.File.ReadAllText(@"projectTest.json");
var collection = Database.GetCollection<BsonDocument>("Forecasts");
var redact = BsonDocument.Parse(redactJson);
var project = BsonDocument.Parse(projectJson);
var aggregatonPipeline = collection.Aggregate();
aggregatonPipeline.AppendStage<BsonDocument>(redact);
aggregatonPipeline.AppendStage<BsonDocument>(project);
var list = aggregatonPipeline.ToList();
或类似的代码
var pipeline = collection.Aggregate().AppendStage<BsonDocument>(redact);
pipeline.AppendStage<BsonDocument>(project);
var list = pipeline.ToList();
我的聚合json看起来像这些
redactTest.json:
{
$redact: {
$cond: {
if: {
$gt: [{ $size: { "$setIntersection": [ "$tags", ["STLW", "G"]]}}, 0]
},
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
projectTest.json
{
"$project":
{
"_id": 0,
"title": 1,
"year": 1,
"subsections.subtitle": 1,
"subsections.content": 1
}
}
源文件是
{
_id: 1,
title: "123 Department Report",
tags: [ "G", "STLW" ],
year: 2014,
subsections: [
{
subtitle: "Section 1: Overview",
tags: [ "SI", "G" ],
content: "Section 1: This is the content of section 1."
},
{
subtitle: "Section 2: Analysis",
tags: [ "STLW" ],
content: "Section 2: This is the content of section 2."
},
{
subtitle: "Section 3: Budgeting",
tags: [ "TK" ],
content: {
text: "Section 3: This is the content of section3.",
tags: [ "HCS" ]
}
}
]
}
答案 0 :(得分:3)
collection.Aggregate()
公开了流畅的聚合接口,并通过方法链将各阶段附加到管道。
像
这样的东西var pipeline= collection.Aggregate().AppendStage<BsonDocument>(redact).AppendStage<BsonDocument>(project);
var list = pipeline.ToList();
一次添加一个阶段时,您的用法将覆盖之前的阶段。