简短的回答,是的,但前提是所有文件都是新的。如果没有,就会一一插入或更新。
看一眼SimpleMongo存储库 (Mongo存储库的默认实现):
public <S extends T> List<S> saveAll(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities not be null!");
Streamable<S> source = Streamable.of(entities);
boolean allNew = source.stream().allMatch((it) -> {
return this.entityInformation.isNew(it);
});
if (allNew) {
List<S> result = (List)source.stream().collect(Collectors.toList());
return new ArrayList(this.mongoOperations.insert(result, this.entityInformation.getCollectionName()));
} else {
return (List)source.stream().map(this::save).collect(Collectors.toList());
}
}
请注意,当所有文档都是新的时,存储库将使用MongoOperations.插入方法 (Mongo模板是实施),然后,如果您查看该方法的代码,您会发现它执行批量插入:
public <T> Collection<T> insert(Collection<? extends T> batchToSave, String collectionName) {
Assert.notNull(batchToSave, "BatchToSave must not be null!");
Assert.notNull(collectionName, "CollectionName must not be null!");
return this.doInsertBatch(collectionName, batchToSave, this.mongoConverter);
}
2021 年更新:
从 spring-data-mongodb 1.9.0.RELEASE(当前为 3.2.2)开始,BulkOperations 附带了许多额外的功能。
如果除了保存一堆文档之外还需要更高级的任务,那么批量操作 https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/BulkOperations.html阶级是必经之路。
它涵盖批量插入、更新和删除:
- 插入(列表文档)
- 删除(列表删除)
- updateMulti(列表>更新)