Connection to non existing mongodb server does not throw exception

java, mongodb, mongodb-java

Solution

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.

Problem

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.

Original source