C# MongoDb更新方法无法正常工作
我在项目中使用mongoDB,在代码中使用Collection.Update方法,但它不能正常工作,有时会失败,代码粘贴如下:C# MongoDb更新方法无法正常工作,c#,mongodb,C#,Mongodb,我在项目中使用mongoDB,在代码中使用Collection.Update方法,但它不能正常工作,有时会失败,代码粘贴如下: collections.Update(Query.EQ("_id", ObjectId.Parse(databaseid)),Update.Set("agent",ip)) 如果我尝试在这一行之后添加代码,可能在大多数情况下都能正常工作: Thread.Sleep(2000); 那么问题出在哪里呢?您使用的是传统的MongoDB驱动程序。驱动程序的当前版本是2.0.
collections.Update(Query.EQ("_id", ObjectId.Parse(databaseid)),Update.Set("agent",ip))
如果我尝试在这一行之后添加代码,可能在大多数情况下都能正常工作:
Thread.Sleep(2000);
那么问题出在哪里呢?您使用的是传统的MongoDB驱动程序。驱动程序的当前版本是2.0.1,它具有。因此,您可以等待数据库操作,而无需线程休眠和猜测需要多长时间。假设您有一个类,其属性
Id
类型为ObjectId
,属性Agent
类型为string
:
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
}
private异步任务DoSomething(ObjectId,string ip)
{
MongoClient=新的MongoClient(connectionString);
var db=client.GetDatabase(“databaseName”);
var collection=db.GetCollection(“collectionName”);
var update=Builders.update.Set(x=>x.Agent,ip);
var result=await collection.UpdateOneAsync(x=>x.Id==Id,update);
//您可以在此处检查更新结果
}
所以,只需更新驱动程序并使用新的异步API即可