It is necessary through a connection string to connect to some server. For this, I use the following code.

using MongoDB.Driver; // ... static MongoClient client; public static bool Connect(string connectionString) { client = new MongoClient(connectionString); return client != null; } 

The question is: is it correct to check the success of the connection by comparing the client variable with null ? Are there any other nuances to consider when connecting?

  • The documentation on MongoClient does not say anything about this. But it is easy to check. Pass the obviously incorrect connection string and see what happens. And the client has a ListDatabases() method, as I understand it, if the connection is successfully established, you can get a list of databases on the server. - Bulson
  • You have just created an instance of the class. It will not be null under any circumstances. Perhaps the constructor will throw an exception, but, again, you will not get to check for null. - Vlad

2 answers 2

As stated here , you need:

 public static Task<bool> CheckConnectionAsync(string connectionString, string dbName) { var client = new MongoClient(connectionString); var database = client.GetDatabase(dbName); return database.RunCommandAsync((Command<BsonDocument>)"{ping:1}"); } 

    Synchronous version of the method:

      private static Boolean MongoDbConnection(String connectionString, String dbName) { var client = new MongoClient(connectionString); for (int k = 0; k < 6; k++) { client.GetDatabase(dbName); var server = client.Cluster .Description .Servers .FirstOrDefault(); if (server != null && server.HeartbeatException == null && server.State == ServerState.Connected) { break; } Thread.Sleep(300); } return false; } 

    Asynchronous version of the method:

      private static async Task<Boolean> MongoDbConnectionAsync(String connectionString, String dbName) { return await Task.Run(() => { var client = new MongoClient(connectionString); for (int k = 0; k < 6; k++) { client.GetDatabase(dbName); var server = client.Cluster .Description .Servers .FirstOrDefault(); if (server != null && server.HeartbeatException == null && server.State == ServerState.Connected) { break; } Thread.Sleep(300); } return false; }); } 
    • one
      Can you explain what your code does? In particular, it is not clear why the for loop is needed and why only false is returned. - J. Doe Nov.
    • It looks weird: run the task and make Wait . Then you can just throw the creation task. - Alexander Petrov
    • @Alexander Petrov, I fully agree with you, you can make it easier, for example - Yaroslav
    • @J. Doe, checks the connection to the database, the cycle is needed so that the condition can be met, if the condition is true, then an interrupt occurs, otherwise it returns false - Yaroslav
    • one
      Taska is not needed . Or, you need to return Task<T> , and the caller will decide how to wait for it to complete (via await , Result or Wait ). - Alexander Petrov