Connection to non existing mongodb server does not

2019-05-23 08:21发布

I'm playing around a bit with the MongoDB driver for Java. So I just created a simple application to connect to a MongoDB server and select a database.
So I created an instance of MongoClient and selected a 'DB':

try
{
    MongoClient client = new MongoClient("localhost", 27017);
    DB database = client.getDB("example");
}catch(Exception e){
    e.printStackTrace();
}

Because of the fact that there is no running instance of mongod on my machine, I expected that client would throw an Exception. Unfortunately that isn't the case.
Even when selecting the database nothing happens. It just behaves like if there was a running mongod instance.

I looked into the documentation about the Java driver but couldn't find anything about it. Same with Google.
Is there anything I missed?

I'm using the latest MongoDB driver (version 2.12.2) from the official website.

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-05-23 08:57

Try doing an insert to a collection. Connections are lazily initialized and validated.

查看更多
做自己的国王
3楼-- · 2019-05-23 09:06

It is expected behaviour. The driver does not attempt to connect to the database until it is needed. If you try the mongo shell, you do not get the error if the database does not exist.

When you try to insert a document into a non-existent collection it is created for you automatically and that is when the connection is lazily established. It is first when you actually perform some db operation (find(), insert() etc.) that the connection is checked for.

查看更多
登录 后发表回答