小编典典

如何使用Spring Boot将JSON数据文件导入mongodb?

spring-boot

如您所知,当使用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数据?


阅读 971

收藏
2020-05-30

共1个答案

小编典典

我不知道是否有使用的解决方案,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);
    }
2020-05-30