How to import JSON data files to mongodb with Spring Boot?

放肆的年华 提交于 2020-01-14 16:45:47

问题


As you know, when using spring boot jpa module, below codes in application.properties import pre-defined sql data to rdb.

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

But when using mongodb as storage, what properties codes in application.properties file can import pre-defined JSON data of external files? If such properties do not exit, how can the JSON data be imported from the external files with spring boot?


回答1:


I don't know if there is a solution using application.properties but here is my solution to import documents from a file containing one document per line.

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



回答2:


You can have a look at this following Test class, provided by "flapdoodle". The test shows how to import a JSON file containing the collection dataset: MongoImportExecutableTest.java

You could theoretically also import a whole dump of a database. (using MongoDB restore): MongoRestoreExecutableTest.java



来源:https://stackoverflow.com/questions/54722783/how-to-import-json-data-files-to-mongodb-with-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!