saving & updating full json document with Spring data MongoTemplate

2.2k views Asked by At

I'm using Spring data MongoTemplate to manage mongo operations. I'm trying to save & update json full documents (using String.class in java).

Example:

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

I know that I can update code & variables independently using:

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

But due to our application architecture, it could be more useful for us to directly replace the full object. As I know:

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

implements saveOrUpdate functionality, but this creates two objects, do not update anything.

I'm missing something? Any approach? Thanks

1

There are 1 answers

2
Harsh Patel On

You can use Following Code :

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

There may be some other way to get keyset from json, you can use according to your convenience.

You can use BasicDbObject to get keyset.

you can get BasicDbObject using mongoTemplate.getConverter().