MongoDB (server v 2.6.7) with C # 2.0 driver: how to get the result from InsertOneAsync

I am testing MongoDB (server v 2.6.7) using the C # 2.0 driver.

When I use the insert function InsertOneAsync for a document with _id that exists, I expect an error similar to the one you get from the Mongo shell:

 WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.Commands.$_id_ dup key: { : 0.0 }" }}) 

But the problem is that inserting with the C # driver does not throw an exception, and I cannot find the WriteResult to insert. When I look into the database, nothing seems to have happened.

So my question is what to expect from InsertOneAsync when inserting an existing _id ?

Code in Visual Studio:

 IMongoCollection<BsonDocument> commandsCollection = db.GetCollection<BsonDocument>("Commands"); var bson = new BsonDocument { {"_id", i.Value}, {"label", i.Key} }; commandsCollection.InsertOneAsync(bson); 
+7
c # mongodb async-await mongodb-.net-driver
source share
4 answers

If you do this using the async method, then the brp output will work (and is preferred), otherwise you can call Wait() on the Task returned from the InsertOneAsync call InsertOneAsync that your application remains long enough to see a duplicate key exception:

 commandsCollection.InsertOneAsync(doc).Wait(); 

If the insertion fails due to a duplicate key, Wait() throw an AggregateException that contains a MongoWriteException that contains the duplicate key's data.

 try { commandsCollection.InsertOneAsync(doc).Wait(); } catch(AggregateException aggEx) { aggEx.Handle(x => { var mwx = x as MongoWriteException; if (mwx != null && mwx.WriteError.Category == ServerErrorCategory.DuplicateKey) { // mwx.WriteError.Message contains the duplicate key error message return true; } return false; }); } 

Similarly, if you use await , this will also throw an AggregateException .

To avoid the additional complexity of an AggregateException wrapping an mongo exception, you can call GetAwaiter().GetResult() instead of Wait() :

 try { commandsCollection.InsertOneAsync(doc).GetAwaiter().GetResult(); } catch(MongoWriteException mwx) { if (mwx.WriteError.Category == ServerErrorCategory.DuplicateKey) { // mwx.WriteError.Message contains the duplicate key error message } } 
+9
source share

This is an async task, you are missing the expected

 await commandsCollection.InsertOneAsync(bson); 

https://github.com/mongodb/mongo-csharp-driver/blob/master/README.md

+2
source share

In addition to @JonnyHK's answer, you can do the same when pasting many.

 collection.InsertManyAsync(doc, new InsertManyOptions { IsOrdered = false }).Wait(); 

will be wrapped in try / catch;

 try { collection.InsertManyAsync(doc, new InsertManyOptions { IsOrdered = false }).Wait(); } catch (AggregateException aggEx) { aggEx.Handle(x => { var mwx = x as MongoBulkWriteException; return mwx != null && mwx.WriteErrors.All(e => e.Category == ServerErrorCategory.DuplicateKey); }); } 
+1
source share

I am using VS 2015 and have tried adding data completely with InsertOne / InsertOneAsync, but none of them work.

The code is here: // Create a MongoClient object using the connection string _client = new MongoClient ();

  //Use the MongoClient to access the server _database = _client.GetDatabase("ratednext"); //get mongodb collection var Collec = _database.GetCollection<BsonDocument>("computers"); var documnt = new BsonDocument { {"Brand","Dell"}, {"Price","400"}, {"Ram","8GB"}, {"HardDisk","1TB"}, {"Screen","16inch"} }; try { Collec.InsertOneAsync(documnt).GetAwaiter().GetResult(); } catch (AggregateException aggEx) { aggEx.Handle(x => { var mwx = x as MongoWriteException; if (mwx != null && mwx.WriteError.Category == ServerErrorCategory.DuplicateKey) { // mwx.WriteError.Message contains the duplicate key error message return true; } return false; }); } 
0
source share

All Articles