2017-01-17 11 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 
        }} 
       ); 
      } 
     } 
    } 
関連する問題