简体   繁体   English

使用C#驱动程序部分mongodb upsert?

[英]Partial mongodb upsert using the c# driver?

Mongo version 1.8.2. Mongo版本1.8.2。

Assume I have a class like 假设我有一个像

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
};

I'd like to call 我想打电话

myCollection.Save(a), 

such that 这样的

  • if it doesn't exist, its inserted (easy so far) 如果不存在,则将其插入(到目前为止很容易)
  • if it does exist, Foo is updated, but, but Bar remains whatever it currently is (perhaps non-null...) 如果确实存在,则Foo会更新,但是,Bar仍然保持当前状态(也许非null ...)

How do I achieve this partial upsert? 我该如何实现部分局部验证?

Many thanks. 非常感谢。

It would be quite easy to do it with 2 successive updates : 连续进行2次更新非常容易:

myCollection.Insert(a,SafeMode.False);
myCollection.Update(Query.EQ("_id",a._id), Update.Set("Foo",a.Foo))

You have to use the SafeMode.False to ensure that if a exists in the collection, the insert won't raise an exception. 您必须使用SafeMode.False来确保如果集合中存在a,则插入不会引发异常。

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. 起初,您会认为这些操作的顺序很重要,但并不重要:如果首先执行2,无论其结果如何,1都会无声地失败。

However I don't have clue on how to use the save method to do this direclty. 但是我不知道如何使用save方法执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM