Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MongoClient.getDatabase() return just a DB instance or actually creates it?

Tags:

java

mongodb

In order to create a database instance in MongoDB 3.2 you have to write something like that:

new MongoClient().getDatabase("dbName");

According to the official MongoDB Java API 3.2 this should return you a database instance.

My questions:

  1. Do I understand correctly, that if the DB with the specified name does not exist, thus MongoDB will create it for me?

  2. And if the assumption from the question #1 is correct, what will happen if I'll try to request the same DB twice? Will it return just the already existed instance or will drop the existed one and will create a new one?

P.S. Can you, please, advise me a good and updated MongoDB for Java manual/tutorial, I googled for a couple of them, but they are not so updated.

like image 942
Mike Avatar asked May 11 '26 17:05

Mike


1 Answers

In 3.1.1 driver:

Calling getDatabase doesn't in fact create new database because operation is lazy - it returns database representation. Calling any modifiable operation (e.g. createCollection):

  1. will create new database for you if it is not present
  2. if present it will get database for you

But remember that you have to call any operation which actually performs something - like create. If you just call getDatabase it won't create it.

like image 125
k0ner Avatar answered May 14 '26 08:05

k0ner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!