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

当我对存在InsertOneAsync的文档使用插入函数_id时,我期望出现类似您从Mongo shell中得到的错误:



但是问题是,使用C#驱动程序进行插入不会引发异常,并且我找不到该插入的WriteResult
当我查看数据库时,似乎什么都没发生。

所以我的问题是,在插入现有的InsertOneAsync时对_id有什么期望?

Visual Studio中的代码:

IMongoCollection<BsonDocument> commandsCollection = db.GetCollection<BsonDocument>("Commands");
var bson = new BsonDocument
        {
            {"_id", i.Value},
            {"label", i.Key}
        };
commandsCollection.InsertOneAsync(bson);

最佳答案

如果您在async方法中执行此操作,则Brduca的答案将起作用(并且是更可取的),否则您可以对Wait()调用返回的Task调用 InsertOneAsync ,以确保您的应用程序停留的时间足够长,以查看重复的键异常:

commandsCollection.InsertOneAsync(doc).Wait();

如果由于重复键而导致插入失败,则Wait()将抛出一个AggregateException,该MongoWriteException包含一个包含重复键详细信息的await
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;
    });
}

同样,如果您使用的是AggregateException,那么也会抛出一个AggregateException

为了避免包裹mongo异常的GetAwaiter().GetResult()的复杂性增加,您可以调用Wait()而不是ojit_code:
try
{
    commandsCollection.InsertOneAsync(doc).GetAwaiter().GetResult();
}
catch(MongoWriteException mwx)
{
    if (mwx.WriteError.Category == ServerErrorCategory.DuplicateKey)
    {
        // mwx.WriteError.Message contains the duplicate key error message
    }
}

10-04 22:29
查看更多