MongoDB的用C#2.0的驱动程序(v服务器2.6.7):如何从InsertOneAsync结果 [英] MongoDB (server v 2.6.7) with C# driver 2.0: How to get the result from InsertOneAsync

查看:1339
本文介绍了MongoDB的用C#2.0的驱动程序(v服务器2.6.7):如何从InsertOneAsync结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C#2.0的驱动程序测试的MongoDB(v服务器2.6.7)。

当我使用插入功能 InsertOneAsync 与文档的 _id 它存在我期待一个错误就像一个你从蒙戈外壳得到:


  WriteResult({
    nInserted:0,
    writeError:{
            code:11000,
            ERRMSG:insertDocument ::引起:: 11000 E11000重复键错误指数:mydb.Commands $ _ ID_ DUP键:{:0.0}
    }})


但问题是,随着C#驱动程序插入不会抛出异常,我无法找到 WriteResult 的插入。
当我看到在数据库中似乎没有发生。

我的问题是,从 InsertOneAsync期待什么插入时现有的 _id

在code在Visual Studio:

  IMongoCollection< BsonDocument> commandsCollection = db.GetCollection< BsonDocument>(命令);
VAR BSON =新BsonDocument
        {
            {_id,i.Value},
            {标签,i.Key}
        };
commandsCollection.InsertOneAsync(BSON);


解决方案

如果你的中这样做异步方法,那么Brduca的回答就可以了(并且是preferrable),否则你可以调用 等待() 上的工作从返回的 InsertOneAsync 打电话,以确保您的应用程序保持足够长的时间看到重复键异常:

  commandsCollection.InsertOneAsync(DOC).Wait();

如果插入失败,因为重复键时,等待()将抛出一个 AggregateException 包含 MongoWriteException 包含重复的关键细节。

 尝试
{
    commandsCollection.InsertOneAsync(DOC).Wait();
}
赶上(AggregateException aggEx)
{
    aggEx.Handle(X =>
    {
        VAR MWX = x作为MongoWriteException;
        如果(MWX = NULL&放大器;!&安培; mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
        {
            // mwx.WriteError.Message包含重复键错误信息
            返回true;
        }
        返回false;
    });
}

同样,如果你使用等待,这将抛出一个 AggregateException 以及

要避免 AggregateException 包装蒙戈异常,可以拨打 GetAwaiter()调用getResult()而不是等待()

 尝试
{
    commandsCollection.InsertOneAsync(文件).GetAwaiter()调用getResult();
}
赶上(MongoWriteException MWX)
{
    如果(mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
    {
        // mwx.WriteError.Message包含重复键错误信息
    }
}

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);

解决方案

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
    }
}

这篇关于MongoDB的用C#2.0的驱动程序(v服务器2.6.7):如何从InsertOneAsync结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆