【问题标题】:MongoDB push to nested array using Linq expressionsMongoDB 使用 Linq 表达式推送到嵌套数组
【发布时间】:2019-01-17 11:51:19
【问题描述】:

要使用 de MongoDB C# Driver 执行推送,我需要实例化 FieldDefinition<MyMongoDocumentType, MyNestedArrayType[]>

我知道我可以使用字符串实例化这个FieldDefinition...

FieldDefinition<MyMongoDocumentType, NestedArrType[]> field = "MyArray.$.MyNestedArray";

我也尝试过使用 Linq 表达式,如下所示:

FieldDefinition<MyMongoDocumentType, NestedArrType[]> field =
    new ExpressionFieldDefinition<MyMongoDocumentType, NestedArrType[]>(
        doc => doc.MyArray.First().MyNestedArray
    );

但我得到了这个错误:

System.InvalidOperationException:无法确定 doc => 的序列化信息 doc.MyArray.First().MyNestedArray.

有没有办法使用行之有效的 Linq 表达式创建嵌套数组的 FieldDefinition

【问题讨论】:

    标签: c# mongodb linq mongodb-.net-driver


    【解决方案1】:

    您可以使用-1作为数组索引来表示位置运算符($):

    FieldDefinition<MyMongoDocumentType, NestedArrType[]> field =
                new ExpressionFieldDefinition<MyMongoDocumentType, NestedArrType[]>(
                    doc => doc.MyArray[-1].MyNestedArray
                );
    

    要使其正常工作,您还需要在 MyArray 上附加查询条件,这可以在 MongoDB .NET 驱动程序中使用 ElemMatch 来完成,例如:

    Builders<MyMongoDocumentType>.Filter.ElemMatch(x => x.MyArray, f => f.NestedId == 1);
    

    【讨论】:

    • 它有效,谢谢!我建议在文件开头使用#pragma warning disable CS0251,在文件末尾使用#pragma warning restore CS0251,以避免对负索引的警告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2020-03-27
    相关资源
    最近更新 更多