我正在尝试使用C#驱动程序创建一个mongodb聚合管道,该驱动程序包括修订后的项目.我尝试了如下所示的几种方法,但是在每种情况下,仅执行管道的第一阶段. AppendStage似乎不会追加下一阶段.那么,如何使用C#mongodb驱动程序编写一个后跟项目的项目.请注意,流畅的界面不直接支持编辑,但另一篇文章显示了使用下面的代码来实现这一点,该文章适用于第一阶段.
我正在使用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" ]
}
}
]
}
解决方法:
collection.Aggregate()公开流利的聚合接口,并通过方法链接将阶段附加到管道中.
就像是
var pipeline= collection.Aggregate().AppendStage<BsonDocument>(redact).AppendStage<BsonDocument>(project);
var list = pipeline.ToList();