使用C#驱动程序部分mongodb upsert? [英] Partial mongodb upsert using the c# driver?
本文介绍了使用C#驱动程序部分mongodb upsert?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Mongo版本1.8.2
Mongo version 1.8.2.
假设我有一个类似
public class Acc
{
public int _id { get; set; }
public int? Foo { get; set; }
public int? Bar{ get; set; }
}
Acc a = new Acc
{
_id = 1,
Foo = 3
};
我想打电话
myCollection.Save(a),
这样
- 如果不存在,则将其插入(到目前为止很容易)
- 如果确实存在,则会对Foo进行更新,但是,Bar仍然保持当前状态(可能是非null ...)
如何实现部分局部更新?
How do I achieve this partial upsert?
非常感谢.
推荐答案
使用2个连续的更新很容易做到:
It would be quite easy to do it with 2 successive updates :
myCollection.Insert(a,SafeMode.False);
myCollection.Update(Query.EQ("_id",a._id), Update.Set("Foo",a.Foo))
您必须使用SafeMode.False来确保如果集合中存在a,则插入不会引发异常.
You have to use the SafeMode.False to ensure that if a exists in the collection, the insert won't raise an exception.
起初,您会认为这些操作的顺序很重要,但并不重要:如果首先执行2,无论其结果如何,1都会无声地失败.
At first you would think the order of these operations is important but it isn't : if 2 is executed first, whatever its result, 1 will silently fail.
但是我不知道如何使用save方法执行此操作.
However I don't have clue on how to use the save method to do this direclty.
这篇关于使用C#驱动程序部分mongodb upsert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文