If I want to import a CSV file from the command line I simply use:
mongoimport -d <database> -c <collection name> --type csv --file <path to csv> --headerline
Of course headerline
is optional. In my case, the CSV files do have a header.
How can I do the same via C#? Is there a similar one line command? I know how to read a CSV file but I'm surprised I cannot find (a single?) simple command(s).
I have looked at a lot of the online documentation but much of it seems to be for a different .NET driver version; mine is version 2.2.4.
Here is the long way around code so far (it works but I'm thinking it can be 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 to csv")); // where <full path to csv> is the file path, of course
IMongoCollection<BsonDocument> csvFile = db.GetCollection<BsonDocument>("test");
reader.ReadLine(); // to 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 this format is that I must have exactly four columns - which I cannot guarantee.
The perfect answer will include a way to skip the header row.
In case it is relevant: I'm looking to import multiple CSV files so I will find each in a directory - but I know how to do that.