如何在MongoDB C#聚合管道中使用Addfields

编程入门 行业动态 更新时间:2024-10-27 03:37:22
本文介绍了如何在MongoDB C#聚合管道中使用Addfields的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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?

推荐答案

如此处所述在MongoDB Driver for C#中使用$ addFields ,您可以使用BsonDocument自己构建聚合阶段.

As discussed here Using $addFields in MongoDB Driver for C# you can build the aggregation stage yourself with a BsonDocument.

要使用 docs.mongodb上的示例/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

本文发布于:2023-11-22 09:38:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:道中   如何在   MongoDB   Addfields

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!