Jan 19, 2015

Bulk Insert – Save DataTable to MongoDB – C# MongoDB Driver 2.1

Do you want to import csv or excel (xls, xlsx) file in MongoDB? You can read the file, get the data in C# datatable and save it to MongoDB using InsertBatch method. This article explains how to save C# DataTable to MongoDB for inserting a large amount of data.

To install Official .NET driver for MongoDB, run the following command in the Package Manager Console

Install-Package MongoDB.Driver

In your application configuration file, add mongodb connectionstring

  <add key="mongoConnection" value="mongodb://localhost" />

Now use following method:

  public async Task SaveDataTableToCollection(DataTable dt)
        {
            var connectionString = ConfigurationManager.AppSettings["mongoConnection"];
            var client = new MongoClient(connectionString);
            var database = client.GetDatabase("myMongoDatabaseName");

            var collection = database.GetCollection<BsonDocument>("MyCollection");

            List<BsonDocument> batch = new List<BsonDocument>();
            foreach (DataRow dr in dt.Rows)
            {
                var dictionary = dr.Table.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => dr[col.ColumnName]);
                batch.Add(new BsonDocument(dictionary));
            }

            await collection.InsertManyAsync(batch.AsEnumerable());
        }

You can call the above method and pass the datatable to save in MongoDB. To get DataTable from CSV/excel file, read following posts:

Upload and Read CSV File in ASP.NET MVC
Upload and Read Excel File (.xls, .xlsx) in ASP.NET MVC

Hope it helps.

  • Hash

    i tried above code, with passing the datatable, I do not see it inserts any rows I have in datatable to MongoDB
    here is the code:

    public void readSQLDataforImport()
    {
    DataTable sourceTable = SqlReadDB(connectionString, TSQL);
    SaveDataTableToCollection(sourceTable);
    }

    public async void SaveDataTableToCollection(DataTable dt)
    {
    var client = new MongoClient(“mongodb://mongodbserver:27017”);

    var database = client.GetDatabase(“CentralCollection”);

    var collection = database.GetCollection(“Emailrecipients”);
    collection.WithWriteConcern(WriteConcern.Acknowledged);

    List batch = new List();

    foreach (DataRow dr in dt.Rows)
    {
    var dictionary = dr.Table.Columns.Cast().ToDictionary(col => col.ColumnName, col => dr[col.ColumnName]);
    batch.Add(new BsonDocument(dictionary));
    }

    await collection.InsertManyAsync(batch.AsEnumerable());
    }