首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MongoWriteException: InsertOne将MongoDB.Driver.MongoBulkWriteException作为内部异常

MongoWriteException: InsertOne将MongoDB.Driver.MongoBulkWriteException作为内部异常
EN

Stack Overflow用户
提问于 2022-07-21 09:47:14
回答 1查看 196关注 0票数 0

原始例外:

MyMicroServiceMigrator.Services.MainBackgroundService失败:

写入操作导致错误。WriteError:{DuplicateKey,代码: 11000,消息:"E11000重复密钥收集: VrcProd.mycollection索引: id键:{ _id: ObjectId('62d70fb8e12940a8ab7527d6') }“}。

内部例外:

MongoDB.Driver.MongoBulkWriteException1[Models.VRC.Collections.MyCollection]: A bulk write operation resulted in one or more errors. WriteErrors: [ { Category : "DuplicateKey", Code : 11000, Message : "E11000 duplicate key error collection: VrcProd.mycollection index: _id_ dup key: { _id: ObjectId('62d70fb8e12940a8ab7527d6') }" } ]. at MongoDB.Driver.MongoCollectionImpl1.BulkWrite(IClientSessionHandle会话,IEnumerable1 requests, BulkWriteOptions options, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass28_0.b__0(IClientSessionHandle会话( MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSession[TResult](Func2 func ),MongoDB.Driver.MongoCollectionImpl1.BulkWrite(IEnumerable1请求( CancellationToken cancellationToken),MongoDB.Driver.MongoCollectionBase1.<>c__DisplayClass68_0.<InsertOne>b__0(IEnumerable1请求( BulkWriteOptions options,CancellationToken cancellationToken),MongoDB.Driver.MongoCollectionBase1.InsertOne(TDocument document, InsertOneOptions options, Action2 bulkWrite( BulkWriteOptions bulkWriteOptions) )

所以问题是为什么在调用MongoBulkWriteException时会有InsertOne作为内部异常?

向上插入方法:

代码语言:javascript
运行
复制
    public void Upsert<T>(T entity, bool newEntity = false) where T : IMongoEntityVRC
    {
        try
        {
            if (newEntity)
            {
                this.Insert(entity);
            }
            else
            {
                this.FindAndUpdate(entity);
            }
        } catch (MongoWriteException e) when (ExceptionUtils.GetErrorCode(e) == DuplicateKeyCode)
        {
            throw new EntityUniqueConstraintViolationException(e.Message);
        }
    }

我不会发布调用者方法的全部代码,因为它不相关。但是,从一种类型(类型A)映射到新类型(B类型)非常简单。

代码语言:javascript
运行
复制
   // pseudo code of the caller method:
   foreach (var item in items)
   {
      // find existing
      var myEntity = FindmyEntity(item.id);
      // map the object of the new type from this entity
      var mappedEntity = CreateEntity(myEntity ?? new MappedEntity(), myEntity);
      // upsert or insert depending if existing entity was found
      Upsert(entity, myEntity is null);
   }

现在我的问题是,我打电话给MongoBulkWriteException时,为什么要得到InsertOne,这没有任何意义.

EN

回答 1

Stack Overflow用户

发布于 2022-07-21 12:51:22

所有的CRD (在CRUD中)操作都是通过Bulk内部完成的。因此,当您调用Insert时,您实际上调用了一个Bulk操作。这就是你看到MongoBulkWriteException的原因

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73064018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档