1

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.

i3arnon
  • 113,022
  • 33
  • 324
  • 344
Nik
  • 2,718
  • 23
  • 34

1 Answers1

3

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.

kamaradclimber
  • 2,479
  • 1
  • 26
  • 45