Reputation: 1018
I use mongoDB in my project,and I use Collection.Update method in my code,but it not work properly, it will fail at sometimes,the code is pasted below:
collections.Update(Query.EQ("_id", ObjectId.Parse(databaseid)),Update.Set("agent",ip))
If I tried to add code after this line maybe it will work at most of time:
Thread.Sleep(2000);
so where is the problem?
Upvotes: 0
Views: 1028
Reputation: 236218
You are using legacy MongoDB driver. Current version of driver is 2.0.1 and it has new async API. So you can await database operations without thread sleeping and guessing how long it will take. Assume you have some class with properties Id
of type ObjectId
and Agent
of type 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
}
So, just update your driver and use new async API.
Upvotes: 2