拯救和使用Spring数据更新完整的json文档MongoTemplate

时间:2015-06-18 08:11:54

标签: spring mongodb spring-data mongotemplate

我正在使用Spring数据MongoTemplate来管理mongo操作。我正在努力保存&更新json完整文档(在java中使用String.class)。

示例:

String content = "{MyId": "1","code":"UG","variables":[1,2,3,4,5]}";
String updatedContent = "{MyId": "1","code":"XX","variables":[6,7,8,9,10]}";

我知道我可以更新代码&变量独立使用:

Query query = new Query(where("MyId").is("1"));

Update update1 = new Update().set("code", "XX");
getMongoTemplate().upsert(query, update1, collectionId);

Update update2 = new Update().set("variables", "[6,7,8,9,10]");
getMongoTemplate().upsert(query, update2, collectionId);

但是由于我们的应用程序架构,直接替换整个对象对我们来说可能更有用。据我所知:

getMongoTemplate().save(content,collectionId) 
getMongoTemplate().save(updatedContent,collectionId) 

实现saveOrUpdate功能,但这会创建两个对象,不会更新任何内容。

我错过了什么?任何方法?感谢

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

ActiveSheet.PivotTables("Sales").PivotFields("[Buying].[MCH].[MCH3]"). _
    CurrentPageName = "[Buying].[MCH].[MCH3].[X]"

从json获取Query query = new Query(); query.addCriteria(Criteria.where("MyId").is("1")); Update update = new Update(); Iterator<String> iterator = json.keys(); while(iterator.hasNext()) { String key = iterator.next(); if(!key.equals("MyId")) { Object value = json.get(key); update.set(key, value); } } mongoTemplate.updateFirst(query, update, entityClass); 可能还有其他方法,您可以根据自己的方便使用。

您可以使用keyset获取BasicDbObject

您可以使用keyset获取BasicDbObject