title: Import CSV file to Mongo database
body: <p>If I want to import a CSV file from the command line I simply use:</p>
  
  <pre><code>mongoimport -d &lt;database&gt; -c &lt;collection name&gt; --type csv --file &lt;path to csv&gt; --headerline
  </code></pre>
  
  <p>Of course <code>headerline</code> is optional. In my case, the CSV files do have a header.</p>
  
  <p>How can I do the same via C#? Is there a similar one line command? I know how to <a href="https://stackoverflow.com/a/5283044/283650">read a CSV file</a> but I'm surprised I cannot find (a single?) simple command(s).</p>
  
  <p>I have looked at a lot of the <a href="https://docs.mongodb.com/getting-started/csharp/" rel="nofollow noreferrer">online documentation</a> but much of it seems to be for a different .NET driver version; mine is version 2.2.4.</p>
  
  <p>Here is the <em>long way around</em> code so far (it works but I'm thinking it can be done more easily):</p>
  
  <pre><code>MongoClient client = new MongoClient("mongodb://127.0.0.1:27017/test"); // local database
  var db = client.GetDatabase("test");
  
  var reader = new StreamReader(File.OpenRead(@"&lt;full path to csv")); // where &lt;full path to csv&gt; is the file path, of course
  IMongoCollection&lt;BsonDocument&gt; csvFile = db.GetCollection&lt;BsonDocument&gt;("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);
  }
  </code></pre>
  
  <p>One disadvantage of this format is that I must have exactly four columns - which I cannot guarantee.</p>
  
  <p>The perfect answer will include a way to <a href="https://stackoverflow.com/a/9093253/283650">skip the header row</a>.</p>
  
  <p><sub>In case it is relevant: I'm looking to import multiple CSV files so I will find each in a directory - <a href="https://stackoverflow.com/a/929418/283650">but I know how to do that</a>.</sub></p>