Search code examples
c#mongodbmongodb-.net-driver

Update with AddToSet not updating null value with MongoDB C#


Using MongoDB, I'm having trouble adding en element to an Array when the array is null. AddToSet works as expected if I add the item from the console. I am using the official C# driver from 10gen.

var query = Query.EQ("_id", objectId);          
var itemDoc = item.ToBsonDocument();

//items is an array but currently null
var update = MongoDB.Driver.Builders.Update.AddToSet("items", itemDoc); // YUNoWork?

//somefield doesn't exist
var workingUpdate = MongoDB.Driver.Builders.Update.AddToSet("somefield", itemDoc); //works fine

var collection = DataBase.GetCollection<MyObject>(CollectionName);

collection.Update(query, update); // doesn't work
collection.Update(query, workingUpdate); // works

Is this expected behavior? If so, is there a more general way to add items to an array?


Solution

  • Did some digging, according to some other comments - like you say, if the element doesn't exist, it works, but if it's null - it doesn't work. Apparently this is by design.

    One suggestion was to add the BsonIgnoreIfNull attribute to arrays, which will mean your AddToSet will then work.