I can drop a database with the following statement:
MongoClient mongo = new MongoClient("localhost", 27017);
mongo.dropDatabase("d");
How can I create a database?
I can drop a database with the following statement:
MongoClient mongo = new MongoClient("localhost", 27017);
mongo.dropDatabase("d");
How can I create a database?
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.
You can create MongoDB database from java with the following code it will be successful but one catch a Mongo database should contain a single collection to display the database while querying.
`MongoClient client = MongoClients.create(CONNECTION_URL);
System.out.println("Connection with database established successfully");`
String databaseName = "SK_BANK_LTD";
System.out.println("Trying to create a database :- "+databaseName);
MongoDatabase db = client.getDatabase(databaseName);
By running the following code the database wont be visible as it does not contain any collection so add a dummy collection in the database while creating a database by `MongoClient client = MongoClients.create(CONNECTION_URL); System.out.println("Connection with database established successfully");
String databaseName = "SK_BANK_LTD";
System.out.println("Trying to create a database :- "+databaseName);
MongoDatabase db = client.getDatabase(databaseName);
Document test = new Document().append("createdBy", "Binson");
db.getCollection("test").insertOne(test);
System.out.println("Database: " + databaseName + "created successfully");`
Make sure your database does not contain the following characters which are prohibited by mongoDB.
'\0', '/', '\', ' ', '"', '.'