如何使用 Spring 引导将 JSON 数据文件导入到 mongodb?
How to import JSON data files to mongodb with Spring Boot?
如您所知,当使用 spring 引导 jpa 模块时,下面 application.properties
中的代码将预定义的 sql 数据导入 rdb。
spring.datasource.initialization-mode = always
spring.datasource.data = classpath:/sql/spring-boot-mysql.sql
但是当使用mongodb作为存储时,application.properties
文件中的哪些属性代码可以导入外部文件的预定义JSON数据?如果这些属性不存在,JSON 数据如何从外部文件中导入 spring 引导?
您可以查看以下测试 class,由 "flapdoodle" 提供。该测试显示了如何导入包含集合数据集的 JSON 文件:MongoImportExecutableTest.java
理论上您也可以导入数据库的整个转储。 (使用 MongoDB 恢复):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);
}
如您所知,当使用 spring 引导 jpa 模块时,下面 application.properties
中的代码将预定义的 sql 数据导入 rdb。
spring.datasource.initialization-mode = always
spring.datasource.data = classpath:/sql/spring-boot-mysql.sql
但是当使用mongodb作为存储时,application.properties
文件中的哪些属性代码可以导入外部文件的预定义JSON数据?如果这些属性不存在,JSON 数据如何从外部文件中导入 spring 引导?
您可以查看以下测试 class,由 "flapdoodle" 提供。该测试显示了如何导入包含集合数据集的 JSON 文件:MongoImportExecutableTest.java
理论上您也可以导入数据库的整个转储。 (使用 MongoDB 恢复):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);
}