Spring Data Mongo update non-null fields of object?

落爺英雄遲暮 提交于 2020-05-17 05:12:31

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/33899175/spring-data-mongo-update-non-null-fields-of-object

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