c# - Import CSV file to Mongo database -
if want import csv file command line use:
mongoimport -d <database> -c <collection name> --type csv --file <path csv> --headerline
of course headerline
optional. in case, csv files have header.
how can same via c#? there similar 1 line command? know how read csv file i'm surprised cannot find (a single?) simple command(s).
i have looked @ lot of online documentation of seems different .net driver version; mine version 2.2.4.
here long way around code far (it works i'm thinking can done more easily):
mongoclient client = new mongoclient("mongodb://127.0.0.1:27017/test"); // local database var db = client.getdatabase("test"); var reader = new streamreader(file.openread(@"<full path csv")); // <full path csv> file path, of course imongocollection<bsondocument> csvfile = db.getcollection<bsondocument>("test"); reader.readline(); // skip header while (!reader.endofstream) { var line = reader.readline(); var values = line.split(','); bsondocument row = new bsondocument { {"column0", values[0]}, {"column1", values[1]}, {"column2", values[2]}, {"column3", values[3]} }; csvfile.insertone(row); }
one disadvantage of format must have 4 columns - cannot guarantee.
the perfect answer include way skip header row.
in case relevant: i'm looking import multiple csv files find each in directory - but know how that.
you use command on cmd? suggest create .bat file streamwriter
execute .bat file process.start()
, passing filename parameter.
way better: execute on commandline use snippet
string command = ""; //enter command want system.diagnostics.process process = new system.diagnostics.process(); system.diagnostics.processstartinfo startinfo = new system.diagnostics.processstartinfo(); startinfo.windowstyle = system.diagnostics.processwindowstyle.hidden; startinfo.filename = "cmd.exe"; startinfo.arguments = "/c " + command; process.startinfo = startinfo; process.start();
Comments
Post a Comment