Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i create mongodb database from java

Tags:

java

mongodb

I can drop a database with the following statement:

MongoClient mongo = new MongoClient("localhost", 27017);
mongo.dropDatabase("d");

How can I create a database?

like image 642
adnan Avatar asked Jan 28 '26 01:01

adnan


1 Answers

If you are using driver 3.1.1 or later:

Refer to this answer:

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

will create new database for you if it is not present 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.

NOTE

The documentation does not provide this information, hopefully, they update it. But long answer short, it only creates it after you call an operation on it.

like image 163
Eduardo Dennis Avatar answered Jan 29 '26 14:01

Eduardo Dennis



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!