简体   繁体   English

Java MongoDB一次保存多个文档

[英]Java MongoDB save multiple documents at once

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.我在 MongoTemplate 中看到了 save() 但它一次可以处理一个文档。 Is there any way to save multiple documents at once or i need to call save in loop ?有没有办法一次保存多个文档,或者我需要在循环中调用保存?

Thanks for all the help.感谢所有的帮助。

I was able to do it using Spring data MongoDB.我能够使用 Spring 数据 MongoDB 来做到这一点。 Spring data MongoDB's MongoRepository has many inbuilt methods. Spring Data MongoDB 的 MongoRepository 有很多内置方法。

org.springframework.data.mongodb.repository.MongoRepository.saveAll(Iterable entites) is the one which i used to save multiple documents. org.springframework.data.mongodb.repository.MongoRepository.saveAll(Iterable entites) 是我用来保存多个文档的那个。

This is one way to do.这是一种方法。

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

You might want to check out BulkWriteOperation class as well.您可能还想查看BulkWriteOperation类。

You can use insertAll of MongoTemplate or ReactiveMongoTemplate , but you have to use it with caution.您可以使用insertAllReactiveMongoTemplateMongoTemplate ,但必须谨慎使用。 It does what it's name stands for - it inserts all documents.它做它的名字所代表的 - 它插入所有文档。 If you call save method then the save has optimistic locking, so it checks if you don't override the document that you shouldn't (if it has the @Version annotation).如果您调用save方法,则save具有乐观锁定,因此它会检查您是否不覆盖不应该覆盖的文档(如果它具有@Version注释)。 insertAll doesn't check for optimistic locking so you can use it as long as you really want to do an insert eg persist documents that aren't persisted yet or you don't care about overriding those documents and optimistic locking. insertAll不检查乐观锁定,因此您可以使用它,只要您确实想要进行插入,例如持久化尚未持久化的文档,或者您不关心覆盖这些文档和乐观锁定。 If you care about optimistic locking then all you can do is to call save for each document which will generate a lot of I/O operations, but that's what it takes to make sure that you will update documents with matching version.如果您关心乐观锁定,那么您所能做的就是为每个文档调用save ,这将生成大量 I/O 操作,但这就是确保您将更新具有匹配版本的文档所需要的。 Also you have to remember that insertAll actually inserts new documents, meaning that you can't update document using this method, because you'll get duplicated key exception.此外,您必须记住insertAll实际上插入了新文档,这意味着您无法使用此方法更新文档,因为您将获得重复的键异常。 Currently spring mongo lacks a feature that would allow to update all the documents (you can only 'insert' them, so save for the first time)目前 spring mongo 缺少允许更新所有文档的功能(您只能“插入”它们,因此第一次保存)

For Insert:对于插入:

You should use the function InsertMany like:你应该使用函数InsertMany像:

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):对于 Upsert(你需要什么):

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

Using Spring you can easily store multiple documents at once.使用 Spring,您可以轻松地一次存储多个文档。

The Interface is already available with method saveAll and details as under:该接口已经可以使用 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);
//...
}

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使用产品实体的“列表”调用保存方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM