Update with AddToSet not updating null value with MongoDB C#

ぃ、小莉子 提交于 2020-01-03 09:56:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9917804/update-with-addtoset-not-updating-null-value-with-mongodb-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!