how to import csv file into mongodb in Java

China☆狼群 提交于 2019-12-12 19:11:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!