使用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?
推荐答案做了一些挖掘工作,根据其他评论-就像您说的那样,如果该元素不存在,则可以使用,但是如果它为null,则不起作用.显然,这是设计使然.
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#更新空值
发布评论