2017-01-17 45 views
0

我想插入一批文檔,其中一些文檔已經存在於集合中。所以我想要的是要麼忽略它們,要麼就是我想要記錄哪個文檔是重複的,並且如果可能的話繼續插入下一個文檔就是一個更好的解決方案。MongoDB如何插入批處理文件並忽略重複項c#

我看到了一些類似的問題,但沒有一個解決了這個問題。

MongoDB Bulk Insert Ignore Duplicate

MongoDB: how to insert document without repeat

我已經創建自己的哈希屬性,因爲我的文檔的唯一關鍵將是一個多重鍵,所以我積累他們比計算它的哈希值。

我的代碼看起來像這樣的事情:

 const string connectionString = "mongodb://127.0.0.1/localdb"; 

     var client = new MongoClient(connectionString); 

     _database = client.GetDatabase("localdb"); 

     var collection = _database.GetCollection<BsonDocument>("Sales"); 


StringBuilder customValue; 

     foreach (var data in dataCollectionDict) 
     { 
      customValue = new StringBuilder(); 

      customValue.Append(data["col1"]); 
      customValue.Append(data["col2"]); 
      customValue.Append(data["col3"]); 
      customValue.Append(data["col4"]); 
      customValue.Append(data["col5"]); 
      customValue.Append(data["col6"]); 

      data.AddRange(new BsonDocument("HashMultipleKey", SHA256Func(customValue.ToString()))); 
     } 


await collection.Indexes.CreateOneAsync(new BsonDocument("HashMultipleKey", 1), new CreateIndexOptions() { Unique = true, Sparse = true ,}); 


await collection.InsertManyAsync(dataCollectionDict); 

任何幫助將非常感激。

回答

0

所以這是圍繞我找到的工作,不知道如果這是最好的解決方案,我很樂意聽到如果你有更好的方式。

 try 
     { 
      await collection.InsertManyAsync(dataCollectionDict); 
     } 
     catch (Exception ex) 
     { 
      ApplicationInsights.Instance.TrackException(ex); 

      InsertSingleDocuments(dataCollectionDict,collection, dataCollectionQueueMessage); 
     } 
    } 

    private static void InsertSingleDocuments(List<BsonDocument> dataCollectionDict, IMongoCollection<BsonDocument> collection 
     ,DataCollectionQueueMessage dataCollectionQueueMessage) 
    { 
     ApplicationInsights.Instance.TrackEvent("About to start insert individual docuemnts and to find the duplicate one"); 

     foreach (var data in dataCollectionDict) 
     { 
      try 
      { 
       collection.InsertOne(data); 
      } 
      catch (Exception ex) 
      { 
       ApplicationInsights.Instance.TrackException(ex,new Dictionary<string, string>() { 
        { 
         "Error Message","Duplicate document was detected, therefore ignoring this document and continuing to insert the next docuemnt" 
        }, { 
         "FilePath",dataCollectionQueueMessage.FilePath 
        }} 
       ); 
      } 
     } 
    }