Java MongoDB一次保存多个文档



我有一个更新的对象/文档列表,我需要一次保存列表中的所有对象。

我在MongoTemplate中看到save((,但它一次可以占用一个文档。 有没有办法一次保存多个文档,或者我需要调用循环保存?

您可以使用MongoTemplateReactiveMongoTemplateinsertAll,但必须谨慎使用。它做它的名字所代表的 - 它插入所有文档。如果调用save方法,则save具有乐观锁定,因此它会检查您是否不重写不应覆盖的文档(如果它具有@Version批注(。insertAll不会检查乐观锁定,因此只要您真的想插入,就可以使用它,例如,持久化尚未持久化的文档,或者您不关心覆盖这些文档和乐观锁定。如果您关心乐观锁定,那么您所能做的就是为每个文档调用save,这将生成大量 I/O 操作,但这就是确保您将使用匹配版本更新文档所需的条件。 此外,您还必须记住,insertAll实际上会插入新文档,这意味着您无法使用此方法更新文档,因为您将获得重复的键异常。目前,Spring mongo缺少允许更新所有文档的功能(您只能"插入"它们,因此请首次保存(

感谢您的所有帮助。

我能够使用Spring数据MongoDB来做到这一点。 Spring data MongoDB的MongoRepository有许多内置的方法。

org.springframework.data.mongodb.repository.MongoRepository.saveAll(Iterable entites( 是我用来保存多个文档的那个。

使用Spring,您可以轻松地一次存储多个文档。

该界面已经可用,方法saveAll和详细信息如下:

@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);
//...
}

弹簧使用示例:

@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());
}
}

您的存储库界面:

//https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html
public interface Repository extends MongoRepository<ProductEntity, String> {   
}

使用产品实体的"列表"调用保存方法

这是一种方法。

mongoTemplate.getCollection("your_collection_name").insert(List<Documents>)

您可能还想查看 BulkWriteOperation 类。

对于插入:

你应该使用函数 插入许多像:

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);

对于更新插入(您需要的(:

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); 
})

最新更新