0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.