1

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

It works, thank you! I recommend using #pragma warning disable CS0251 at the beginning of the file and #pragma warning restore CS0251 at the end, to avoid the warning on the negative index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.