我正在使用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
}
}