You can update your code to use <S extends T> List<S> save(Iterable<S> entites); to save all objects. Spring MongoRepository will take care of all possible cases based on the presence of the _id field and its value.
Further information here https://docs.mongodb.com/manual/reference/method/db.collection.save/
This will work just fine for basic save operations. You do not need to download a document to update. Just set the identifier and be sure to include all the fields for updating, updating it, replacing the existing document.
Simplified domain object:
@Document(collection = "study") public class Study { @Id private String id; private String name; private String value; }
Repository:
public interface StudyRepository extends MongoRepository<Study, String> {}
Imagine you have an existing entry with _id = 1
Collection status until:
{ "_id" : 1, "_class" : "com.mongo.Study", "name" : "saveType", "value" : "insert" }
Run all possible cases:
public void saveStudies() { List<Study> studies = new ArrayList<Study>(); --Updates the existing record by replacing with the below values. Study update = new Study(); update.setId(1); update.setName("saveType"); update.setValue("update"); studies.add(update); --Inserts a new record. Study insert = new Study(); insert.setName("saveType"); insert.setValue("insert"); studies.add(insert); --Upserts a record. Study upsert = new Study(); upsert.setId(2); upsert.setName("saveType"); upsert.setValue("upsert"); studies.add(upsert); studyRepository.save(studies); }
Collection status after:
{ "_id" : 1, "_class" : "com.mongo.Study", "name" : "saveType", "value" : "update" } { "_id" : 3, "_class" : "com.mongo.Study", "name" : "saveType", "value" : "insert" } { "_id" : 2, "_class" : "com.mongo.Study", "name" : "saveType", "value" : "upsert" }