2016-06-21 66 views
-2

我需要使用C#將數據插入到MongoDB Collection。 的問題是,我有數據表的一些記錄,我想插入這些記錄到MongoDB的 任何人可以幫助我 THX所有使用c#在Mongo DB中插入DataTable#

+0

谷歌並不能幫助你去嘗試用於此目的的一些基本的代碼? :)) –

+0

請參閱[this](http://stackoverflow.com/questions/37932924/how-to-solve-mongodb-related-issue-efficiently)並請添加一些東西到您的問題。謝謝。 – profesor79

回答

0

嘗試谷歌,爲e.g,您可以使用下面的代碼。

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

和配置文件:

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