问题
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