问题
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
回答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.
回答2:
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.
来源:https://stackoverflow.com/questions/34489954/how-to-import-csv-file-into-mongodb-in-java