c# - 在 mongo 中插入 doc 时 E11000 重复键错误收集
问题描述
var doc = new BsonDocument();
documentRepository.AddDocument(doc, "myCollection").GetAwaiter().GetResult();
public async Task<string> AddDocument(BsonDocument item, string collection)
{
await _database.GetCollection<BsonDocument>(collection).InsertOneAsync(item);
return item["_id"].ToString(); // this is where exception happens
}
E11000 duplicate key error collection: myApp.myCollection index: id dup key: { _id: ObjectId('12381e2b09f14f0001fead43') } MongoDB.Driver.MongoWriteException: 写入操作导致错误。
E11000 duplicate key error collection: myApp.myCollection index: _id_ dup key: { _id: ObjectId('12381e2b09f14f0001fead43') }
---> MongoDB.Driver.MongoBulkWriteException`1[MongoDB.Bson.BsonDocument]: A bulk write operation resulted in one or more errors.
E11000 duplicate key error collection: myApp.myCollection index: _id_ dup key: { _id: ObjectId('12381e2b09f14f0001fead43') }
at MongoDB.Driver.MongoCollectionImpl`1.BulkWriteAsync(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionBase`1.InsertOneAsync(TDocument document, InsertOneOptions options, Func`3 bulkWriteAsync)
混乱来自这样一个事实,即异常消息说我正在尝试执行批量插入
MongoDB.Driver.MongoBulkWriteException`1[MongoDB.Bson.BsonDocument]
如您所见,我是否只插入一个文档
解决方案
发生此异常是因为您试图_id
在集合中包含重复的值(您可以使用 mongo shell 进行检查)。上面的代码本身并不能触发这个错误,但是如果你调用AddDocument
两次或多次就会出现这个错误。请注意,在第一次 AddDocument 调用之后,item
文档将具有_id
值填充,因此在下次尝试使用此对象时,驱动程序将尝试插入具有重复值的文档
推荐阅读
- python - 如何使用 `np.choose` 或 `np.take` 或类似方法在 numpy 中对它进行矢量化?
- sql - 检索新值时触发器在 PLSQL 中不起作用
- github - 拒绝主 -> 主(先获取)在 GitHub 中面临这个问题
- python - 如何将服务器端 API 添加到 Django 管理网站?
- python-3.x - 如何在输入字段中保留信息 - Python/Selenium
- perl - perl 中的可否定选项
- properties - 这是一种反模式/代码气味吗?- 使用枚举/常量类通过 [] 而不是使用点属性访问类属性
- openssl - openssl CSR 生成给出 Expecting: CERTIFICATE REQUEST
- python - Macbook ModuleNotFoundError 上的致命 Python 错误:没有名为“编码”的模块
- typescript - 基于模板变量的打字稿强制函数返回类型