2015-10-16 73 views
0

我使用MongoDB的在我的项目,我用Collection.Update方法在我的代码,但它不能正常工作,它会在有时会失败,代码粘贴如下:MongoDB的更新方法无法正常工作

collections.Update(Query.EQ("_id", ObjectId.Parse(databaseid)),Update.Set("agent",ip)) 

Thread.Sleep(2000); 

所以问题出在哪里:

如果我想这行后添加代码,也许它会在大部分时间工作吗?

回答

2

您正在使用旧版MongoDB驱动程序。当前版本的驱动程序是2.0.1,它有new async API。所以你可以等待数据库操作而不用线程休眠并猜测需要多长时间。假设你有一些类的属性ObjectIdIdstringAgent

private async Task DoSomething(ObjectId id, string ip) 
{ 
    MongoClient client = new MongoClient(connectionString); 
    var db = client.GetDatabase("databaseName"); 
    var collection = db.GetCollection<YourClass>("collectionName"); 
    var update = Builders<YourClass>.Update.Set(x => x.Agent, ip); 
    var result = await collection.UpdateOneAsync(x => x.Id == id, update); 
    // you can check update result here 
} 

所以,只要更新驱动程序,并使用新的异步API。