1
votes
 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: A write operation resulted in an error.

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)

The confusion comes from the fact that the exception message says that I'm trying to perform bulk insertion

MongoDB.Driver.MongoBulkWriteException`1[MongoDB.Bson.BsonDocument]

whether I'm inserting only one doc as you can see

1
Is that the actual ObjectId?Joe
yes, it is.....user1765862

1 Answers

1
votes

This exception happens because you're trying to have the duplicated _id value in your collection (you may check this with the mongo shell). The above code itself cannot trigger this error, but this error will happen if you call AddDocument twice or more times. Pay attention that after the first AddDocument call, the item document will have _id value-filled, so in the next attempt of using this object, the driver will attempt to insert the document with the duplicated value