MongoDB C# driver and filtered positional operator $[<identifier>] with typed API

Viewed 675

I have a MongoDB collection that has documents that look like the following:

{
    "Name" : "Name1",
    "AA" : [ 
        {
            "B" : {
                "Name" : "Name2"
            },
            "CC" : [ 
                {
                    "Field" : "Value"
                }
            ]
        }
    ]
}

I am working from C# with the 2.7 MongoDB driver.

I want to push an element to the CC array of those elements of AA that match a certain condition. I was able to do that with following code:

[TestFixture]
class TestClass
{
    [Test]
    public void Test()
    {
        var b = new B { Name = "Name2" };
        var c = new C { Field = "Value2" };

        var field = new StringFieldDefinition<Document>("AA.$[element].CC");
        var updateDefinition = Builders<Document>
            .Update
            .Push(field, c);

        var arrayFilterBson = new BsonDocument("element.B",
            new BsonDocument("$eq", b.ToBsonDocument()));
        var arrayFilter = new BsonDocumentArrayFilterDefinition<AgentRecord>(arrayFilterBson);

        var documentFilter = Builders<Document>.Filter.Eq(r => r.Name, "Name1");

        var updateOptions = new UpdateOptions 
        { 
            IsUpsert = false,
            ArrayFilters = new ArrayFilterDefinition[] {  arrayFilter }
        };

        var settings = new MongoClientSettings
        {
            Server = new MongoServerAddress("localhost", 27000)
        };

        var mongoClient = new MongoClient(settings);
        var database = mongoClient.GetDatabase("so-question");
        var collection = database.GetCollection<Document>("collection");
        collection.UpdateOne(documentFilter, updateDefinition, updateOptions);
    }
}

// Mapping classes
public class Document
{
    public string Name { get; set; }
    public A[] AA { get; set; }
}

public class A
{
    public B B { get; set; }
    public C[] CC { get; set; }
}

public class B
{
    public string Name { get; set; }
}

public class C
{
    public string Field { get; set; }
}

Is there a way to achieve the same through the typed API to avoid having to hardcode the name of the fields in definitions such as AA.$[element].CC or element.B?

I am of course worried about having to change these hard-coded expressions when the name of the properties of the classes change or for example if I make use of the [BsonElement("name")] attribute to control the name of the mapped property.

0 Answers
Related