【问题标题】:Map projection result with mongodb C# driver使用 mongodb C# 驱动程序映射投影结果
【发布时间】:2017-03-23 10:53:32
【问题描述】:

我需要将集合中的一些文档映射到简化文档。 我可以在 mongo shell 中获得我需要的东西:

db.getCollection('items').aggregate([
{ "$project": {
    "Team": "$TeamId",
    "Marker": "$Properties.marker.Value"
}}
])

我需要使用 C# 驱动程序(版本 2.3.0)获得相同的结果;我试过这个

var aggregation = m_database.GetCollection<BsonDocument>("items").Aggregate();
var projectionDefinition = new BsonDocument("$project", new BsonDocument
            {
                { "Team", "$TeamId"},
                { "Marker", "$Properties.marker.Value" }
            });

 var query = aggregation.Project(projectionDefinition);
 var result = await query.ToListAsync();

但我收到以下错误

命令聚合失败:$project 的顶层不允许使用 $expressions

有人知道这是怎么回事?

【问题讨论】:

    标签: c# .net mongodb mongodb-.net-driver map-projections


    【解决方案1】:

    如果您致电 Project,您的 bson 中确实已经有 $project, 所以你只需简化你的 projectionDefinition:

    var projectionDefinition = new BsonDocument
            {
                { "Team", "$TeamId"},
                { "Marker", "$Properties.marker.Value" }
            };
    

    我的个人意见:我会避免使用纯 bson,MongoDB 驱动程序为您提供了使用您的 c# dto 类的可能性。

    【讨论】:

    • 谢谢!我复制了一些将我拉向错误方向的代码。我同意避免使用纯 bson 的建议(这是我通常做的,但在这种情况下,纯 bson 对我来说更可行)
    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2017-03-06
    • 1970-01-01
    • 2015-06-07
    相关资源
    最近更新 更多