Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 如何使用Spring Boot将JSON数据文件导入mongodb?_Spring Boot_Spring Mongodb - Fatal编程技术网

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

Spring boot 如何使用Spring Boot将JSON数据文件导入mongodb?,spring-boot,spring-mongodb,Spring Boot,Spring Mongodb,正如您所知,在使用spring boot jpa模块时,下面的代码位于application.properties中,将预定义的sql数据导入rdb spring.datasource.initialization-mode = always spring.datasource.data = classpath:/sql/spring-boot-mysql.sql 但是当使用mongodb作为存储时,application.properties文件中的哪些属性代码可以导入外部文件的预定义JSO

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

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


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

我不知道是否有使用
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);
    }
publicstaticvoidimportdocumentsfromjsonfile(文件){
//读取json文件的每一行。每个文件都是一个观察文档。
List observationDocuments=new ArrayList();
try(BufferedReader br=new BufferedReader(new FileReader(file.getPath());){
弦线;
而((line=br.readLine())!=null){
observationDocuments.add(Document.parse(行));
}
}捕获(IOEX异常){
例如getMessage();
}
mongoTemplate.getCollection(“yourCollection”).insertMany(观察文档);
}

我还有更多问题。我正在使用MongoRepository接口。但是MongoRepository.save或insert方法会对Document objects参数抛出错误。知道吗?我不知道。我建议您发布另一个记录了错误的问题并让我知道。您使用的是哪个
文档
类?我得到
对于
org.springframework.data.mongodb.core.mapping.Document
org.w3c.dom.Document
类型的文档,方法解析(字符串)是未定义的。它可能是mongo java驱动程序API的
org.bson.Document
?是的,它是mongo java驱动程序API的
org.bson.Document
,如果我没有错的话,它是Spring data mongodb的对等依赖项。