Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

When I am using the insert function InsertOneAsync for a document with an _id which exists I am expecting an error like 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 the insert with the C# driver does not throw an exception and I can not find the WriteResult for the insert. When I look in the database it seems nothing have happened.

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

The code in Visual Studio:

IMongoCollection<BsonDocument> commandsCollection = db.GetCollection<BsonDocument>("Commands");
var bson = new BsonDocument
        {
            {"_id", i.Value},
            {"label", i.Key}
        };
commandsCollection.InsertOneAsync(bson);
like image 740
Fredrik Avatar asked May 07 '15 13:05

Fredrik


People also ask

How much RAM do I need for MongoDB server?

MongoDB requires approximately 1 GB of RAM per 100.000 assets. If the system has to start swapping memory to disk, this will have a severely negative impact on performance and should be avoided.

Is MongoDB 5 backwards compatible?

This change is not backwards compatible.

Which version of MongoDB is compatible with Windows 7?

Determine which MongoDB build you need. The following MongoDB builds are available for Windows: MongoDB for Windows 64-bit runs only on Windows Server 2008 R2, Windows 7 64-bit, and newer versions of Windows.

How do I start MongoDB server in Windows?

Inside this folder, you have the bin directory containing mongod.exe. To start MongoDB Server in Windows, start Mongo Daemon (mongod.exe) using the following command: C:\> "C:\Program Files\MongoDB\Server\4.0\bin\mongod.exe" Note that the program we are running is mongod.exe and not mongo.exe.

What is the community version of MongoDB?

MongoDB Community Server The Community version of our distributed database offers a flexible document data model along with support for ad-hoc queries, secondary indexing, and real-time aggregations to provide powerful ways to access and analyze your data. The database is also offered as a fully-managed service with MongoDB Atlas.

How do I use MongoDB with C?

You can add the driver to your application to work with MongoDB in C. Download the required libraries, libmongoc and libbson, from mongoc.org or set up a runnable project by following our tutorial. See Installing the MongoDB C Driver (libmongoc) and BSON library (libbson).

What are the required files to run MongoDB?

In MongoDB, it contains only executable files 10 Plus (exe) in the bin folder. This is true, and That are the required files to MongoDB, it's really hard to believe for a developer like me Who eats from a relation database background.


2 Answers

If you're doing this within an async method, then Brduca's answer will work (and is preferrable), otherwise you can call Wait() on the Task returned from the InsertOneAsync call to ensure your application stays around long enough to see the duplicate key exception:

commandsCollection.InsertOneAsync(doc).Wait();

If the insert fails because of a duplicate key, the Wait() will throw an AggregateException that contains a MongoWriteException that contains the duplicate key details.

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're using await, that will throw an AggregateException as well.

To avoid the added complexity of the AggregateException wrapping the 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
    }
}
like image 61
JohnnyHK Avatar answered Sep 23 '22 05:09

JohnnyHK


This is an async Task, you're missing the await

await commandsCollection.InsertOneAsync(bson);

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

like image 34
brduca Avatar answered Sep 24 '22 05:09

brduca