使用 spring 的 mongoTemplate 或其他方式如何对现有的 mongo 文档执行简单合并?
当我说合并时,我希望发生以下情况:
- 如果修饰符文档中的字段存在于文档的后端版本中,则使用修饰符中的新值对其进行更新。
- 如果修饰文档中的字段在后端版本中不存在,则添加该字段。
- 保留后端文档上的所有其他字段。
使用 spring 的 mongoTemplate 或其他方式如何对现有的 mongo 文档执行简单合并?
当我说合并时,我希望发生以下情况:
你想执行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的字段,它会执行更新。如果用户没有该字段,则会将该字段添加到文档中。
我已经用 spring boot 1.4 测试过了
如果您想使用 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");
您基本上是在使用 $set 来更新您传递的对象中的所有现有值。我不确定它是否是最优雅的方式,但它工作正常。
我没有在这里介绍 upsert 案例,因为我假设您知道该文档已经存在以便创建您的更新标准。