2017-05-12 67 views
0

這一個不斷出現。我的操作是作爲upsert來完成的,但是每隔一段時間,服務就會崩潰,因爲它遇到了這個錯誤,我不明白它甚至是可能的。我嘗試做使用SurveyId作爲其中關鍵的UPSERT匹配:爲什麼這個upsert會失敗並出現重複的id異常?

await _surveyRepository.DatabaseCollection.UpdateOneAsync(
    Builders<SurveyData>.Filter.Eq(survey => survey.SurveyId, surveyData.SurveyId), 
    Builders<SurveyData>.Update 
     .Set(survey => survey.SurveyLink, surveyData.SurveyLink) 
     .Set(survey => survey.ClientId, surveyData.ClientId) 
     .Set(survey => survey.CustomerFirstName, surveyData.CustomerFirstName) 
     .Set(survey => survey.CustomerLastName, surveyData.CustomerLastName) 
     .Set(survey => survey.SurveyGenerationDateUtc, surveyData.SurveyGenerationDateUtc) 
     .Set(survey => survey.PortalUserId, surveyData.PortalUserId) 
     .Set(survey => survey.PortalUserFirst, surveyData.PortalUserFirst) 
     .Set(survey => survey.PortalUserLast, surveyData.PortalUserLast) 
     .Set(survey => survey.Tags, surveyData.Tags), 
    new UpdateOptions { IsUpsert = true }) 
.ConfigureAwait(false); 

我會偶爾出現此錯誤:

Message: A write operation resulted in an error. E11000 duplicate key error collection: surveys.surveys index: SurveyId dup key: { : "" }

的ID是一個GUID的字符串表示和在mongo中設置爲唯一。

那麼爲什麼會發生這種情況呢?這是我的理解,如果它找到了關鍵,它會更新定義的屬性,如果沒有,它會插入。這是不正確的?因爲,那是我需要的效果。

C#驅動程序版本是2.4.1.18

回答

0

It is my understanding that if it finds the key, it'll update the defined properties, and if not, it'll insert. Is that not correct

是這UPSERT做什麼。新插入的文檔將包含條件的所有字段部分(在您的情況下爲surveyId)以及更新修改爲部分(所有其他指定字段)的更新查詢。
您需要在查詢中設置upsert = false。然後它只會更新符合條件的文檔,如果找不到匹配項,更新將失敗。

+0

這不是預期的效果。這只是一個更新;我需要一個upsert。如果找到id,它應該用指定的數據更新記錄,如果找不到,則插入一個帶有提供的字段的新記錄。它永遠不會失敗。 – Sinaesthetic

1

這是因爲根據該Jira ticket

During an update with upsert:true option, two (or more) threads may attempt an upsert operation using the same query predicate and, upon not finding a match, the threads will attempt to insert a new document. Both inserts will (and should) succeed, unless the second causes a unique constraint violation.

+0

那真讓人氣憤......謝謝 – Sinaesthetic

相關問題