问题描述
Mongo DB的Aggregation管道具有"AddFields"阶段,该阶段使您可以将新字段投影到管道的输出文档中,而无需知道已经存在哪些字段.
Mongo DB's Aggregation pipeline has an "AddFields" stage that allows you to project new fields to the pipeline's output document without knowing what fields already existed.
似乎这未包含在Mongo DB的C#驱动程序中(使用2.7版).
It seems this has not been included in the C# driver for Mongo DB (using version 2.7).
有人知道这是否有其他选择吗?也许是项目"阶段的标志?
Does anyone know if there are any alternatives to this? Maybe a flag on the "Project" stage?
推荐答案
如此处所述,您可以使用BsonDocument自己构建聚合阶段.
As discussed here Using $addFields in MongoDB Driver for C# you can build the aggregation stage yourself with a BsonDocument.
要使用 https://docs.mongodb.com上的示例/manual/reference/operator/aggregation/addFields/
{
$addFields: {
totalHomework: { $sum: "$homework" } ,
totalQuiz: { $sum: "$quiz" }
}
}
看起来会像这样:
BsonDocument expression = new BsonDocument(new List<BsonElement>() {
new BsonElement("totalHomeWork", new BsonDocument(new BsonElement("$sum", "$homework"))),
new BsonElement("totalQuiz", new BsonDocument(new BsonElement("$sum", "$quiz")))
});
BsonDocument addFieldsStage = new BsonDocument(new BsonElement("$addFields", expression));
IAggregateFluent<BsonDocument> aggregate = col.Aggregate().AppendStage(addFieldsStage);
表达式是代表BsonDocument的
expression being the BsonDocument representing
{
totalHomework: { $sum: "$homework" } ,
totalQuiz: { $sum: "$quiz" }
}
您可以像往常一样将其他阶段附加到IAggregateFluent对象上
You can append additional stages onto the IAggregateFluent Object as normal
IAggregateFluent<BsonDocument> aggregate = col.Aggregate()
.Match(filterDefintion)
.AppendStage(addFieldsStage)
.Project(projectionDefintion);
这篇关于如何在MongoDB C#聚合管道中使用Addfields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!