Partial mongodb upsert using the c# driver?
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 ach开发者_JAVA百科ieve this partial upsert?
Many thanks.
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.
精彩评论