I have a CSV file, and I'm trying to import the CSV file in the MongoDB database. Unfortunately, the experience is not working as I wish it would. The content of the CSV file is not relevant, since when I use MongoDB Compass to import it manually, there is no issue and it's appearing as I want. Thus, I'm trying to save it from local folder to the MongoDB using Java and Spring Boot if possible, but I can't find any good advice or explaination about how to do so.
I'm using Spring Boot 2.6.3 and Java11.
Thanks a lot.
CodePudding user response:
public class MongoImportUtil {
public static void main(String[] args) {
String Host = "localhost";
String Port = "27017";
String DB = "userDemo";
String CollectionName = "users";
String FileName = "D:/Test.csv";
// Without Credential
String command = "C:\\Program Files\\MongoDB\\Server\\5.0\\bin\\mongoimport.exe --host " Host " --port " Port " --db " DB " --collection " CollectionName " --headerline --type=csv --file " FileName;
// With Credential
/* String command = "C:\\Program Files\\MongoDB\\Server\\5.0\\bin\\mongoimport.exe --host " Host " --port " Port " --db " DB " --collection " CollectionName "--authenticationDatabase admin --username " user " --password " password " --headerline --type=csv --file " FileName; */
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println("Imported csv into Database");
} catch (Exception e) {
System.out.println("Error executing " command e.toString());
}
}
}