MongoDB supports efficient batch operations through bulkWrite, and SimpleMongoRepository.saveAll(...) already performs a batch insert when all entities are new .
However, if entities contains any non-new entity, it calls SimpleMongoRepository.save(...) for each entity, which seems neither efficient nor consistent.
A possible improvement would be something like the following:
List<S> newEntities = new ArrayList<>();
List<S> existingEntities = new ArrayList<>();
// ...
if (!newEntities.isEmpty()) {
mongoOperations.insert(newEntities, entityInformation.getCollectionName());
}
if (!existingEntities.isEmpty()) {
BulkOperations bulkOps = mongoOperations.bulkOps(BulkMode.ORDERED, entityInformation.getJavaType(),
entityInformation.getCollectionName());
for (S entity : existingEntities) {
Query query = new Query(where(entityInformation.getIdAttribute()).is(entityInformation.getId(entity)));
bulkOps.replaceOne(query, entity, FindAndReplaceOptions.options().upsert());
}
bulkOps.execute();
}
MongoDB supports efficient batch operations through bulkWrite, and
SimpleMongoRepository.saveAll(...)already performs a batch insert when all entities are new .However, if entities contains any non-new entity, it calls
SimpleMongoRepository.save(...)for each entity, which seems neither efficient nor consistent.A possible improvement would be something like the following: