Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check connection to mongodb

Tags:

c#

mongodb

I use MongoDB drivers to connect to the database. When my form loads, I want to set up connection and to check whether it is ok or not. I do it like this:

var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("reestr");

But I do not know how to check connection. I tried to overlap this code with try-catch, but to no avail. Even if I make an incorrect connectionString, I still can not get any error message.

like image 845
Jacobian Avatar asked Mar 03 '15 15:03

Jacobian


People also ask

How do I know if my MongoDB database is connected?

isConnected runs getDbObject . getDbObject connects to mongoDB and returns an object: connected (true/false), db (dbObject or error). Then, isConnected resolve/reject by connected property.

How do I connect to a MongoDB database?

To connect to a MongoDB Server using username and password, you have to use 'username@hostname/dbname'. Where username is the username, password is the password for that user and dbname is the database to which you want to connect to. Note : You can use multiple hostname to connect to with a single command.

What is the URL of MongoDB connectivity?

connect('mongodb://localhost:27017/myapp'); This is the minimum needed to connect the myapp database running locally on the default port (27017). If connecting fails on your machine, try using 127.0. 0.1 instead of localhost .


3 Answers

To ping the server with the new 3.0 driver its:

var database = client.GetDatabase("YourDbHere");

database.RunCommandAsync((Command<BsonDocument>)"{ping:1}")
        .Wait();
like image 59
Paul Keister Avatar answered Oct 19 '22 06:10

Paul Keister


There's a ping method for that:

var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
server.Ping();
like image 31
mnemosyn Avatar answered Oct 19 '22 08:10

mnemosyn


full example for 2.4.3 - where "client.GetServer()" isn't available. based on "Paul Keister" answer.

client = new MongoClient("mongodb://localhost");
database = client.GetDatabase(mongoDbStr);
bool isMongoLive = database.RunCommandAsync((Command<BsonDocument>)"{ping:1}").Wait(1000);

if(isMongoLive)
{
    // connected
}
else
{
    // couldn't connect
}
like image 26
Pav K. Avatar answered Oct 19 '22 07:10

Pav K.