0

I am trying to update an array item in a BsonDocument using the UpdateBuilder.AddToSet method. However, the method always insert a new copy of the item in the array instaed of updating the existing.

Here's my object :

    public class Document
    {
       [BsonRepresentation(BsonType.ObjectId)]
       public String _id { get; set; }
       [BsonIgnoreIfNull]
       public List<Event> Events { get; set; }
    }

    public class Event
    {
       [BsonRepresentation(BsonType.ObjectId)]
       public String _id { get; set; }
       [BsonIgnoreIfNull]
       public String Title { get; set; }
    }

And here is how I try to update the array item, based on its _id:

    //tevent is an instance of an existing event, with just the Title changed
    var update = new UpdateBuilder<Document>();
    update.AddToSet<Event>(t => t.Events, tevent);
    var query = Query<Event>.EQ(t => t._id, tevent._id);

    //GetCollection() return the document collection
    var result = GetCollection().Update(query, update, UpdateFlags.Upsert);

As said before, item are added to the array, even if there is an item with the same _id. I would like to update the item with the same _id if already present in the document array.

Raphaël
  • 427
  • 5
  • 14

1 Answers1

0

your code will convert to like: { _id: tevent._id }

I think you should use: var query = Query.EQ("Events._id", tevent._id);

it should convert to like: { Events._id: tevent._id }

your can find C# driver source on github: https://github.com/mongodb/mongo-csharp-driver/blob/531e7b6f1f38934811fa8eb146def5049df332d9/src/MongoDB.Driver.Legacy/Builders/UpdateBuilder.cs

Cologler
  • 724
  • 6
  • 18