问题
I Have a list of updated objects/documents i need save all the objects in the list at once.
I saw save() in MongoTemplate but it can take single document at a time. Is there any way to save multiple documents at once or i need to call save in loop ?
回答1:
Thanks for all the help.
I was able to do it using Spring data MongoDB. Spring data MongoDB's MongoRepository has many inbuilt methods.
org.springframework.data.mongodb.repository.MongoRepository.saveAll(Iterable entites) is the one which i used to save multiple documents.
回答2:
This is one way to do.
mongoTemplate.getCollection("your_collection_name").insert(List<Documents>)
You might want to check out BulkWriteOperation class as well.
回答3:
Using Spring you can easily store multiple documents at once.
The Interface is already available with method saveAll and details as under:
@NoRepositoryBean
public interface MongoRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#saveAll(java.lang.Iterable)
*/
@Override
<S extends T> List<S> saveAll(Iterable<S> entites);
//...
}
Spring usage example:
@Component
public class Processor {
@Autowired
public Processor(Repository repository) {
this.repository= repository;
}
public void save(Iterable<ProductEntity> entites) {
List<ProductEntity> saved = repository.saveAll(entites);
logger.info("Saved {} entities", saved.size());
}
}
your Repository interface:
//https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html
public interface Repository extends MongoRepository<ProductEntity, String> {
}
Call save method with 'List' of Product entities
回答4:
For Insert:
You should use the function InsertMany like:
List<Document> docList = new List<Document>();
docList.add(doc1); // assuming that doc1 and doc2 are defined
docList.add(doc2);
yourMongoDb.getCollection("your_collection").insertMany(docList);
For Upsert (what you need):
UpdateOptions options = new UpdateOptions().upsert(true) ;
yourCollectionOfDocuments.forEach( doc ->{
Document filter = Filters.eq("_id", doc.get("id"));
yourDb.getCollection("your_collection").updateOne(filter,update,option);
})
来源:https://stackoverflow.com/questions/50718892/java-mongodb-save-multiple-documents-at-once