Search code examples
c#mongodbauthenticationmongodb.driver

Getting "TimeoutException" when trying to retrieve data from MongoDB


I'm using C# to connect to a MongoDB server using the official MongoDB.Driver with version 2.2.24.26

My code looks like this:

internal BsonArray Find(string ConnectionString, string collection, string filter)
{
    Uri u = new Uri(ConnectionString);
    string database = u.LocalPath.Trim(new char[] { '/' });
    IMongoDatabase _db = new MongoClient(ConnectionString).GetDatabase(database);
    IMongoCollection<BsonDocument> col = _db.GetCollection<BsonDocument>(collection);
    return BsonArray.Create(col.Find(BsonDocument.Parse(filter)).ToList());
}

It works like charm (it finishes within less than 0.5 seconds) if the connection string is like

mongodb://localhost:27017/my_db

As soon as I want to use authentication, I always encounter a timeout.

mongodb://user:password@localhost:27017/my_db

The operation consuming all the time is the "ToList()". The list in my tests does have 136 entries. Am I missing something?

Edit: Sorry for the wrong topic in the first place. I don't know how a topic from a totally unrelated issue did appear here...


Solution

  • I found the problem. MongoDB seems to give back an TimeoutException if the credentials are invalid. I accidentally added the user I wanted to use to the wrong database and hence I could not log into the original database with it. The exception made me search for the issue in a totally wrong direction :/

    Looks like a strange behavior when using wrong credentials, but that is just my opinion.