首页 文章

带有C#驱动程序2.0的MongoDB(服务器v 2.6.7):如何从InsertOneAsync获取结果

提问于
浏览
9

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

当我使用插入函数 InsertOneAsync 用于存在 _id 的文档时,我期待一个类似于你从Mongo shell获得的错误:

WriteResult({
“nInserted”:0,
“writeError”:{
“代码”:11000,
“errmsg”:“insertDocument ::由:: 11000 E11000引起的重复键错误索引:mydb.Commands . $ _ id_ dup key:{:0.0}”
}})

但问题是带有C#驱动程序的插入不会抛出异常,我找不到插入的 WriteResult . 当我查看数据库时,似乎什么都没发生 .

所以我的问题是在插入现有的 _id 时从 InsertOneAsync 可以期待什么?

Visual Studio中的代码:

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

4 回答

  • 0

    继@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);
        });
    }
    
  • 11

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

    commandsCollection.InsertOneAsync(doc).Wait();
    

    如果插入因重复键而失败, Wait() 将抛出 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 .

    为了避免包含mongo异常的 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
        }
    }
    
  • 2

    这是一个异步任务,你错过了等待

    await commandsCollection.InsertOneAsync(bson);
    

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

  • 1

    我正在使用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<BsonDocument>("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;
                });
            }
    

相关问题