Partial mongodb upsert using the c# driver?

久未见 提交于 2020-01-15 08:59:51

问题


Mongo version 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...)

How do I achieve this partial upsert?

Many thanks.


回答1:


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))

You have to use the SafeMode.False to ensure that if a exists in the collection, the insert won't raise an exception.

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.

However I don't have clue on how to use the save method to do this direclty.



来源:https://stackoverflow.com/questions/7533481/partial-mongodb-upsert-using-the-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!