1

If I have a Java object with only updated fields set, for example (assume there is a third field C that is not set):

obj.setA(1); obj.setB(2);

Is it possible to perform an Update operation that only updates A and B? It appears my only options with Spring Data are to use save() (which would overwrite the value for C in the database to null), or use update(), which requires me to construct an Update object with a set() statement for each field in the object, as well as hardcode Mongo field names. Essentially what I'm looking for is something that would do this update operation:

$set:{'a':1,'b':2}

I was messing around a bit with Reflection to try and do this (looking at the solutions offered here), which could potentially work, but it seems a bit hacky. If Spring Data supports this somehow, I'd rather do that.

Community
  • 1
  • 1
Joseph Blair
  • 1,385
  • 2
  • 12
  • 25

1 Answers1

0

There is o.s.d.m.core.query.Update for exactly that purpose.
From the reference documentation:

// query: { "name" : "Joe" }
// update: { "$set" : { "age" : 35} }
mongoOps.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
Christoph Strobl
  • 6,491
  • 25
  • 33