使用AddToSet更新不会使用MongoDB C#更新空值 [英] Update with AddToSet not updating null value with MongoDB C#
问题描述
使用MongoDB,当数组为null时,无法在数组中添加en元素.如果我从控制台添加项目,则AddToSet会按预期工作.我正在使用10gen的官方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?
推荐答案
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.
一项建议是将 BsonIgnoreIfNull 属性添加到数组,这意味着您的AddToSet将起作用.
One suggestion was to add the BsonIgnoreIfNull attribute to arrays, which will mean your AddToSet will then work.
这篇关于使用AddToSet更新不会使用MongoDB C#更新空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!