【发布时间】:2016-07-19 12:46:49
【问题描述】:
如果我想从命令行导入 CSV 文件,我只需使用:
mongoimport -d <database> -c <collection name> --type csv --file <path to csv> --headerline
当然headerline 是可选的。就我而言,CSV 文件确实有一个标题。
我怎样才能通过 C# 做同样的事情?有没有类似的单行命令?我知道如何read a CSV file,但我很惊讶我找不到(一个?)简单的命令。
我查看了很多 online documentation,但其中大部分似乎是针对不同的 .NET 驱动程序版本;我的是 2.2.4 版。
到目前为止,这是很长的路代码(它有效,但我认为它可以更轻松地完成):
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);
}
这种格式的一个缺点是我必须正好有四列——我不能保证。
完美的答案将包括skip the header row。
如果相关:我希望导入多个 CSV 文件,因此我会在一个目录中找到每个文件 - but I know how to do that。
【问题讨论】:
-
与其在 BsonDocument 构造函数中添加键/值对,不如创建一个包含这些对的 Dictionary
,然后使用 row.AddRange(dictionary) 将其添加到 BsonDocument。