3

I can drop a database with the following statement:

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

How can I create a database?

1
  • Did you really need to copy-paste your question 3 times without formatting? People won't want to deal with your question if looks like that. (Note to others: See edit revisions.) Commented Jul 24, 2017 at 16:17

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("database name");

If database is not present, MongoDB will create it for you.

Comments

0

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', '/', '\', ' ', '"', '.'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.