MongoRepository 的 saveAll() 是批量插入数据吗?

yas*_*eco 4 spring mongodb spring-boot

我想让保存操作高效,所以我想偶尔向 Mongo 写入大量对象(即当超出某些容量时)

saveAll()为我这样做吗?我应该BulkOperations改用吗?

Die*_* M. 9

简短的回答,是的,但前提是所有文件都是新的。如果没有,它会一一插入或更新。

看看SimpleMongoRepositoryMongoRepository 的默认实现):

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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,当所有文档都是新的时,存储库将使用MongoOperations.insert方法(MongoTemplate是实现),然后,如果您查看该方法的代码,您会发现它执行批量插入:

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);
    }
Run Code Online (Sandbox Code Playgroud)

2021 年更新:

从 spring-data-mongodb 1.9.0.RELEASE (current 3.2.2) 开始,BulkOperations 有很多额外的特性。

如果除了保存一堆文档之外还需要更高级的任务,那么BulkOperations类是不错的选择。

它涵盖了批量插入、更新和删除:

  • 插入(列表<?扩展对象>文档)
  • 删除(列表删除)
  • updateMulti(List<Pair<Query,Update>> 更新)

  • 那么如何批量更新呢? (2认同)