使用AddToSet更新不会使用MongoDB C#更新空值

编程入门 行业动态 更新时间:2024-10-25 11:23:09
本文介绍了使用AddToSet更新不会使用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?

推荐答案

做了一些挖掘工作,根据其他评论-就像您说的那样,如果该元素不存在,则可以使用,但是如果它为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#更新空值

本文发布于:2023-11-13 12:11:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AddToSet   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!