[英]C# MongoDB bulk Upsert - A bulk write operation resulted in one or more errors
為什么會這樣
因為在某些情況下,upsert不能自動為您正在操作的對象生成_id。
解決方案A.
在模型的_id字段中使用[BsonIgnoreIfDefault]。
解決方案B.
您可以在使用ObjectId.GenerateNewId()進行upsert之前手動生成_id
更多信息
原始郵政
在官方文檔之后 ,我寫了這個方法。 當我運行它時,我收到這個神秘的錯誤消息: “批量寫入操作導致一個或多個錯誤” 。 知道是什么原因造成的嗎? 一切都很好看。 我已經批量插入和刪除方法正常工作。
public bool BulkUpsertReplaceOne (List<AppModel> records,
string collectionName)
{
try
{
var bulk = _database.
GetCollection(collectionName).
InitializeUnorderedBulkOperation();
foreach(AppModel am in records)
{
IMongoQuery mongoQuery = Query.EQ ("Url", am.Url);
bulk.Find (mongoQuery).Upsert().ReplaceOne(am);
}
bulk.Execute();
return true;
}
catch(Exception e)
{
logger.Info (e.Message);
}
}
編輯完成錯誤
at MongoDB.Driver.Operations.BulkWriteBatchResultCombiner.CreateResultOrThrowIfHasErrors (IEnumerable`1 remainingRequests) in <filename unknown>:line 0
at MongoDB.Driver.Operations.BulkMixedWriteOperation.Execute (MongoDB.Driver.Internal.MongoConnection connection) in <filename unknown>:line 0
at MongoDB.Driver.MongoCollection.BulkWrite (MongoDB.Driver.BulkWriteArgs args) in <filename unknown>:line 0
at MongoDB.Driver.BulkWriteOperation.ExecuteHelper (MongoDB.Driver.WriteConcern writeConcern) in <filename unknown>:line 0
at MongoDB.Driver.BulkWriteOperation.Execute () in <filename unknown>:line 0
at SharedLibrary.Wrappers.MongoDB.MongoDBWrapper.BulkUpsertReplaceOne (System.Collections.Generic.List`1 records, System.String collectionName) in <filename unknown>:line 0"
EDIT2
我不知道這是否相關,但如果我在錯誤后檢查數據庫,則只插入了一個批量upsert項,並且hasObjectId(“000000000000000000000000”)。
版本:MongoDB 2.6.1,MongoC#驅動程序2.0.1
您的AppModel的ID記錄值看起來有問題。 看起來他們失蹤或者所有'000000000000000000000000'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.