连接到不存在的mongodb服务器不会引发异常 [英] Connection to non existing mongodb server does not throw exception
问题描述
我正在玩Java的MongoDB驱动程序。所以我刚刚创建了一个简单的应用程序来连接到MongoDB服务器并选择一个数据库。
所以我创建了一个 MongoClient
的实例并选择了一个'DB ':
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();
}
由于没有 mongod
在我的机器上,我预计客户端
会抛出异常
。不幸的是情况并非如此。
即使选择数据库也没有任何反应。它的行为就像是有一个正在运行的 mongod
实例。
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.
我查看了有关Java驱动程序,但无法找到任何相关信息。与Google相同。
有什么我错过的吗?
I looked into the documentation about the Java driver but couldn't find anything about it. Same with Google.
Is there anything I missed?
我正在使用官方网站上的最新MongoDB驱动程序(版本2.12.2) 。
I'm using the latest MongoDB driver (version 2.12.2) from the official website.
推荐答案
这是预期的行为。在需要之前,驱动程序不会尝试连接到数据库。如果您尝试使用mongo shell,则在数据库不存在时不会收到错误。
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.
当您尝试将文档插入到不存在的集合中时,它会自动为您创建,也就是说连接是懒惰建立的。它是第一次实际执行某些数据库操作( find()
, insert()
等)的连接检查。
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.
这篇关于连接到不存在的mongodb服务器不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!