2017-04-24 110 views
0

使用spring的mongoTemplate或其他方式如何在现有的mongo文档上执行简单合并?Spring MongoTemplate更新合并

当我说合并我想以下情况发生:

  1. 如果文档的后端版本存在修改文件中的字段,然后在修改新的值更新它。
  2. 如果修饰符文档中的某个字段在后端版本中不存在,请添加该字段。
  3. 单独保留后端文档上的所有其他字段。
+0

你有一个明确的逻辑,自己实现它;) – Jaiwo99

回答

0

想要执行upsert,是否正确? 这应该很好地工作:

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

基本上这个查询搜索ID为 “ABC” 的用户。如果用户具有名为addThisField的字段,则会执行更新。如果用户没有该字段,则会将该字段添加到文档中。

我和春天有个开机1.4

1

测试它,如果你想进行使用MongoTemplate你可以做以下的合并:

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

你基本上使用$设置为更新传递的对象中的所有现有值。我不确定它是否是最优雅的方式,但它工作正常。

我没有覆盖这里的插件案例,因为我假设您知道该文档已经存在以创建您的更新条件。