0

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.

Bromania
  • 15
  • 7
  • Use [mongoimport](https://docs.mongodb.com/database-tools/mongoimport/) for that – Wernfried Domscheit Mar 01 '22 at 12:26
  • thanks for the answer, but mongoimport is made to be used is command prompt ! i wish to use it in java, do you know if it's compatible in any way ? – Bromania Mar 01 '22 at 12:42
  • I use mongoimport in a special way. It imports a CSV/JSON **file**, however it works also for input from STDIN, so I compose my JSON string and print to STDOUT of mongoimport process. – Wernfried Domscheit Mar 01 '22 at 12:58
  • I'm really sorry but I don't understand what you mean there. Just so you know, I'm not very experienced with those technologies, and I still don't get how to use mongoimport in my java code... Do you have a documentation somewhere or an exemple to show me ? Thanks a lot – Bromania Mar 01 '22 at 14:31
  • I am not familiar with Java, have a look at https://stackoverflow.com/questions/11336157/running-external-program-with-redirected-stdin-and-stdout-from-java or https://www.rgagnon.com/javadetails/java-0014.html – Wernfried Domscheit Mar 01 '22 at 14:34
  • Thanks a lot for your time. It's working now. Still not exactly as I wanted but I'm working on it ! Have a great day – Bromania Mar 01 '22 at 15:47

1 Answers1

1
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());  
        }  
    }  
}