mongodb - How to update document in mongo to get performance? -


i new spring data mongo. i've scenario want create study if not present in mongo db. if present, i've update new values.

i tried in following way, works fine in case, i'm not sure correct/best/advisable way update etc far performance concerned.

could please guide on this?

public void savestudy(list<study> studies) {         (study study : studies) {             string id = study.getid();             study presentindbstudy = studyrepository.findone(id);              //find document, modify , update save() method.             if(presentindbstudy != null) {                 presentindbstudy.settitle(task.gettitle());                 presentindbstudy.setdescription(study.getdescription());                     presentindbstudy.setstart(study.getstart());                 presentindbstudy.setend(study.getend());                 repository.save(presentindbstudy);             }             else                 repository.save(study);         }     } 

you have use mongotemplate.upsert() achieve this. need add 2 more classes: studyrepositorycustom interface , class extends interface, studyrepositoryimpl

interface studyrepositorycustom {    public writeresult updatestudy(study study); } 

update current studyrepository extend interface

@repository public interface studyrepository extends mongorepository<study, string>, studyrepositorycustom {    // ... code before } 

and add class implements studyrepositorycustom. @autowire our mongotemplate , provide implementation updating study or saving if not exist. use mongotemplate.upsert() method.

class studyrepositoryimpl implements studyrepositorycustom {    @autowired    mongotemplate mongotemplate;     public writeresult updatestudy(study study) {       query searchquery = new query(criteria.where("id").is(study.getid());       writeresult update = mongotemplate.upsert(searchquery, update.update("title", study.gettitle).set("description", study.getdescription()).set(...)), study.class);       return update;    } } 

kindly note studyrepositoryimpl automatically picked spring data infrastructure we've followed naming convention of extending core repository interface's name impl

check this example on github, @autowire-ing mongotemplate , using custom repository above.

i have not tested code guide :-)


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -