Spring MongoTemplate更新合并 [英] Spring MongoTemplate Update Merge

查看:1039
本文介绍了Spring MongoTemplate更新合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用spring的mongoTemplate还是要在现有的mongo文档上执行简单合并?

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. 如果文档的后端版本上存在修饰符文档中的字段,请使用修饰符中的新值对其进行更新.
  2. 如果修改器文档中的字段在后端版本中不存在,请添加该字段.
  3. 仅保留后端"文档上的所有其他字段.

推荐答案

如果您想使用MongoTemplate执行合并,则可以执行以下操作:

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)

示例:

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

基本上,您正在使用$ set来更新要传递的对象中的所有现有值.我不确定这是否是最优雅的方法,但是效果很好.

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.

这里我不讨论upsert案例,因为我假设您知道该文档已经存在,可以创建您的更新条件.

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.

这篇关于Spring MongoTemplate更新合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆