Search code examples
c#mongodbmongodb-.net-driver

insert DataTable in Mongo DB using c#


I need to insert data to MongoDB Collection using C#. Question is, I have data Table with some records , and I want to insert these records to MongoDb Can anybody help me thx all


Solution

  • Try google ,for e.g-you can use below code.

    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());
          }
    

    and in config file:

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