【问题标题】:How to import JSON data files to mongodb with Spring Boot?如何使用 Spring Boot 将 JSON 数据文件导入 mongodb?
【发布时间】:2019-07-10 09:23:21
【问题描述】:

如您所知,在使用spring boot jpa模块时,application.properties中的以下代码将预定义的sql数据导入rdb。

spring.datasource.initialization-mode = always
spring.datasource.data = classpath:/sql/spring-boot-mysql.sql

但是当使用mongodb作为存储时,application.properties文件中的哪些属性代码可以导入外部文件的预定义JSON数据?如果这些属性不退出,那么如何使用spring boot从外部文件中导入JSON数据?

【问题讨论】:

    标签: spring-boot spring-mongodb


    【解决方案1】:

    您可以查看“flapdoodle”提供的以下测试类。测试展示了如何导入包含集合数据集的 JSON 文件:MongoImportExecutableTest.java

    理论上,您也可以导入数据库的整个转储。 (使用 MongoDB 恢复):MongoRestoreExecutableTest.java

    【讨论】:

      【解决方案2】:

      我不知道是否有使用 application.properties 的解决方案,但这是我从每行包含一个文档的文件中导入文档的解决方案。

      public static void importDocumentsFromJsonFile(File file) {
              //Read each line of the json file. Each file is one observation document.
              List<Document> observationDocuments = new ArrayList<>();
              try (BufferedReader br = new BufferedReader(new FileReader(file.getPath()));) {
                  String line;
                  while ((line = br.readLine()) != null) {
                      observationDocuments.add(Document.parse(line));
                  }
              } catch (IOException ex) {
                  ex.getMessage();
              }
              mongoTemplate.getCollection("yourCollection").insertMany(observationDocuments);
          }
      

      【讨论】:

      • 我还有更多问题。我正在使用 MongoRepository 接口。但是 MongoRepository.save 或 insert 方法会引发 Document objects 参数错误。有什么想法吗?
      • 我不知道。我建议您发布另一个记录错误的问题并让我知道。
      • 您使用的是哪个Document 类?我得到The method parse(String) is undefined for the type Documentorg.springframework.data.mongodb.core.mapping.Documentorg.w3c.dom.Document。大概是org.bson.Document
      • 是的,它是 mongo-java-driver API 的 org.bson.document,如果我没记错的话,它是 Spring data mongodb 的对等依赖项。
      猜你喜欢
      • 2014-12-24
      • 2018-09-05
      • 1970-01-01
      • 2020-11-11
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      相关资源
      最近更新 更多