使用spring的mongoTemplate或其他方式如何在現有的mongo文檔上執行簡單合併?Spring MongoTemplate更新合併
當我說合並我想以下情況發生:
- 如果文檔的後端版本存在修改文件中的字段,然後在修改新的值更新它。
- 如果修飾符文檔中的某個字段在後端版本中不存在,請添加該字段。
- 單獨保留後端文檔上的所有其他字段。
使用spring的mongoTemplate或其他方式如何在現有的mongo文檔上執行簡單合併?Spring MongoTemplate更新合併
當我說合並我想以下情況發生:
想要執行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
測試它,如果你想進行使用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");
你基本上使用$設置爲更新傳遞的對象中的所有現有值。我不確定它是否是最優雅的方式,但它工作正常。
我沒有覆蓋這裏的插件案例,因爲我假設您知道該文檔已經存在以創建您的更新條件。
你有一個明確的邏輯,自己實現它;) – Jaiwo99