yogibear
yogibear

Reputation: 340

Mongo UpdateOne for adding a subdocument to array C# using Lambda and FieldDefinition

I am having a problem with field definition with c# mongo driver. My Robo 3T updateOne works just fine, so clearly I understand the mongo side of things.

In essence I need to create a field definition I can use in an updateOn() operation: FieldDefinition<Team> however I should explain what im trying to do which leads to this issue. That way maybe there is a different and more appropriate solution.

The following mongo query works just fine in Robo 3T

db.teams.update({
    _id: ObjectId("607ff1fb313a448aa3312272")
}, {
    $addToSet: {
        Users:         {
            "_id" : ObjectId("603cd341e420290239a2baf0"),
            "id" : 94,
            "first_name" : "Jane",
            "surname" : "Darling",

        }
    }
});

Having proved my understanding I went on to create the following C# code to do this.

            UpdateDefinition<Team> UpdateDefinition 
                = Builders<Team>.Update.
                    AddToSet(x => x.TeamMembers, UserList);
          
            MongoClient.UpdateOne<Team>(
                TeamFilter, 
                UpdateDefinition, 
                CollectionTeam);

If you look at the following post it looks like my assumption is correct on how to specify the array to insert the sub document into: Safely insert or update subdocument in MongoDB

However I get the following error: enter image description here

This is okay with me too, so I tried to create a field definition and I am presently stuck. In theory creating a FieldDefinition should be easy. Except im not finding suitable examples.

In essence this is the method signature im trying to make use of enter image description here

Thanks in advance.

Upvotes: 1

Views: 676

Answers (1)

yogibear
yogibear

Reputation: 340

The solution is very simple

            UpdateDefinition<Team> UpdateDefinition
                = Builders<Team>.Update.
                    AddToSetEach(x => x.TeamMembers, UserList);

The reason it's not easy to find is this that the mongo driver syntax isn't the same as the mongo syntax.

Upvotes: 1

Related Questions