MongoDB 使用 Linq 表达式推送到嵌套数组

MongoDB push to nested array using Linq expressions

要使用 de MongoDB C# 驱动程序执行推送,我需要实例化一个 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: Unable to determine the serialization information for doc => doc.MyArray.First().MyNestedArray.

有没有什么方法可以使用有效的 Linq 表达式创建嵌套数组的 FieldDefinition

您可以使用-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);