Spring MongoTemplate Update Merge

杀马特。学长 韩版系。学妹 提交于 2019-12-25 09:46:10

问题


Using spring's mongoTemplate or otherwise how do I perform a simple merge on an existing mongo document?

When I say merge I want the following to happen:

  1. If a field in modifier document exists on the backend version of the document, then update it with the new value in the modifier.
  2. If a field in the modifier document does NOT exist on the backend version, then add the field.
  3. Leave all other fields on the Backend document alone.

回答1:


If you wanna perform a merge using MongoTemplate you can do the following:

this.mongoTemplate.update**(<your_criteria>, 
Update.fromDBObject(BasicDBObjectBuilder.start("$set", 
<your_object>).get()), <output>.class)

Sample:

BasicDBObject dbObject = new BasicDBObject("a", 1);
Query query = Query.query(Criteria.where("_id").is("123");
Update update = Update.fromDBObject(BasicDBObjectBuilder.start("$set", 
dbObject).get());

this.mongoTemplate.updateFirst(query, update, BasicDBObject.class, 
"my_collection");

You are basically using $set to update all the existing values in the object you are passing. I'm not sure if its the most elegant way to do that but it works fine.

Im not covering the upsert case here because I'm assuming that you know that the document already exists in order to create your update criteria.




回答2:


You want to perform an upsert, correct? This should work fine:

    //suppose that you are trying to get user with Id=abs
    Query query = new Query();
    query.addCriteria(where(ID).is("abc"));

    //and then you can add or update the new field (if the field does not exist, the template adds it into the document)
    Update update = new Update();
    update.set("addThisField", new Date());

    mongo.upsert(query, update, User.class);

Basically this query search for user with id "abc". If the user has the field named addThisField , it performs an update. If the user doesn't have that field, it adds the field into the document.

I have tested it with spring boot 1.4



来源:https://stackoverflow.com/questions/43591032/spring-mongotemplate-update-merge

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