Search code examples
c#mongodblinqmongodb-.net-driver

MongoDB push to nested array using Linq expressions


To execute a push using de MongoDB C# Driver, I need to instantiate a FieldDefinition<MyMongoDocumentType, MyNestedArrayType[]>.

I know that I can instantiate this FieldDefinition using strings...

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

I tried the same using Linq expressions, like this:

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

But I got this error:

System.InvalidOperationException: Unable to determine the serialization information for doc => doc.MyArray.First().MyNestedArray.

Is there any way to create a FieldDefinition of a nested array using Linq expression that works?


Solution

  • You can use -1 as an array index to represent positional operator ($):

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

    To make it work you also need additional query condition on MyArray which can be done using ElemMatch in MongoDB .NET driver, for instance:

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