How do you call the Ping
command with the new C# driver 2.0?
In the old driver it was available via Server.Ping()
? Also, Is there a way to find out if the server is running/responding without running the actual query?
Using mongoClient.Cluster.Description.State
doesn't help because it still gave the disconnected state even after the mongo server started responding.
You can check the cluster's status using its Description
property:
var state = _client.Cluster.Description.State
If you want a specific server out of that cluster you can use the Servers
property:
var state = _client.Cluster.Description.Servers.Single().State;
This worked for me on both c# driver 2 and 1
int count = 0;
var client = new MongoClient(connection);
// This while loop is to allow us to detect if we are connected to the MongoDB server
// if we are then we miss the execption but after 5 seconds and the connection has not
// been made we throw the execption.
while (client.Cluster.Description.State.ToString() == "Disconnected") {
Thread.Sleep(100);
if (count++ >= 50) {
throw new Exception("Unable to connect to the database. Please make sure that "
+ client.Settings.Server.Host + " is online");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With