带有C#驱动程序2.0的MongoDB(服务器v 2.6.7):如何从InsertOneAsync获取结果
我正在使用C#驱动程序2.0测试MongoDB(服务器v 2.6.7)。
当我使用插入函数InsertOneAsync
存在一个存在_id
的文档时,我期待一个像你从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 }" }})
但问题是带有C#驱动程序的插入不会抛出exception,我找不到插入的WriteResult
。 当我查看数据库时,似乎什么都没发生。
所以我的问题是插入现有的_id
时会对InsertOneAsync
什么期望?
Visual Studio中的代码:
IMongoCollection commandsCollection = db.GetCollection("Commands"); var bson = new BsonDocument { {"_id", i.Value}, {"label", i.Key} }; commandsCollection.InsertOneAsync(bson);
如果您在async
方法中执行此操作,那么Brduca的答案将起作用(并且是可取的),否则您可以在InsertOneAsync
调用返回的Task
上调用Wait()
以确保您的应用程序保持足够长的时间以查看重复键例外:
commandsCollection.InsertOneAsync(doc).Wait();
如果插入因重复键而失败,则Wait()
将抛出包含MongoWriteException
的AggregateException
,该MongoWriteException
包含重复的键详细信息。
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; }); }
同样,如果你正在使用await
,那么也会抛出AggregateException
。
为了避免包含mongoexception的AggregateException
复杂性,可以调用GetAwaiter().GetResult()
而不是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 } }
这是一个异步任务,你错过了等待
await commandsCollection.InsertOneAsync(bson);
https://github.com/mongodb/mongo-csharp-driver/blob/master/README.md
继@JonnyHK回复后,你可以在插入很多时做同样的事情。
collection.InsertManyAsync(doc, new InsertManyOptions { IsOrdered = false }).Wait();
将包装在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); }); }
我正在使用VS 2015并尝试使用InsertOne / InsertOneAsync添加数据,但都没有工作。
代码在这里://使用连接字符串_client = new MongoClient()创建一个MongoClient对象;
//Use the MongoClient to access the server _database = _client.GetDatabase("ratednext"); //get mongodb collection var Collec = _database.GetCollection("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; }); }