2

I'm using EclipseLink as API for mongodb. I need to update my database each time from given csv files. Is there any way to import a CSV file into MongoDB with java? or is it possible to execute a raw mongo command like this in java enviroment?

mongoimport --db users --collection contacts --type csv --file /opt/backups/contacts.csv
shohreh
  • 526
  • 9
  • 20

2 Answers2

1
mongoimport --db users --collection contacts --type csv --headerline --file /opt/backups/contacts.csv

--collection parameter is optional. If it is not passed, a collection with filename (without extension) will be created. In this case, the collection name will be "contacts".

--headerline parameter is optional. Specifying --headerline instructs mongoimport to determine the name of the fields using the first line in the CSV file.

Additionally, --ignoreBlanks can be specified to ignore blank fields in CSV.

More information can be found in mongoimport documentation here.

Manish
  • 3,913
  • 2
  • 29
  • 45
  • thanks Manish. But I need to know how to import csv or run that command in my Java code – shohreh Dec 28 '15 at 09:12
  • This command can be executed just like any other executable file can be executed through java. You can use `ProcessBuilder` or `Runtime.exec()` for this. – Manish Dec 28 '15 at 09:54
1

There is no direct way for mongoimport in Java Driver.

Try Runtime.exec(). Sample code:

  Runtime r = Runtime.getRuntime();
  Process p = null;
  String command = "mongoimport --db users --collection contacts --type csv --file /opt/backups/contacts.csv";
  try {
   p = r.exec(command);
   System.out.println("Reading csv into Database");

  } catch (Exception e){
   System.out.println("Error executing " + command + e.toString());
  }

Check out this blog for more details.

Dev
  • 13,492
  • 19
  • 81
  • 174