3

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Joseph Hwang
  • 1,337
  • 3
  • 38
  • 67

2 Answers2

4

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);
    }
charlycou
  • 1,778
  • 13
  • 37
  • I have more question. I am using MongoRepository interface. But MongoRepository.save or insert method throws error with the Document objects parameter. Any idea? – Joseph Hwang Feb 23 '19 at 11:16
  • I have no idea. I suggest you to post another question with the error logged and to let me know. – charlycou Feb 25 '19 at 08:42
  • Which `Document` class are you using? I get `The method parse(String) is undefined for the type Document` for `org.springframework.data.mongodb.core.mapping.Document` and also for `org.w3c.dom.Document`. Is it probably `org.bson.Document`? – kiltek May 21 '19 at 10:06
  • 1
    Yes it's `org.bson.document` of mongo-java-driver API, Whch comes as a peer dependency of Spring data mongodb if I'm not wrong. – charlycou May 21 '19 at 17:50
-1

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

Nijat Mursali
  • 930
  • 1
  • 8
  • 20