gpt4 book ai didi

c# - 如何创建包含 $redact 的 c# mongodb 管道

转载 作者:可可西里 更新时间:2023-11-01 09:34:01 24 4
gpt4 key购买 nike

我正在尝试使用 C# 驱动程序创建一个 mongodb 聚合管道,其中包括 redact 和一个项目。我已经尝试了下面显示的几种方法,但在每种情况下都只执行管道的第一阶段。 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() 公开流畅的聚合接口(interface)并通过方法链将阶段附加到管道。

有点像

var pipeline= collection.Aggregate().AppendStage<BsonDocument>(redact).AppendStage<BsonDocument>(project);
var list = pipeline.ToList();

当一次添加一个阶段时,您的使用会覆盖之前的阶段。

关于c# - 如何创建包含 $redact 的 c# mongodb 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44374650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com