MongoDB Database operations- Create Database, Drop Database

Posted by

The tutorial provides the steps and mongoDB shell command execution to create database in MongoDB, drop database in MongoDB , create and drop statements in MongoDB with examples.

Follow the steps provided in Install MongoDB on Windows Server, Start MongoDB using MongoDB Shell.

Create Database Statement in MongoDB

The MongoDB provides the below given command to create the database. The command will create the New Database if doesn’t exist , else it returns the existing database. MongoDB uses default database as test for storing the documents if no database is created.

Syntax: use DATABASE_NAME

use oracleappshelpDB
switched to db oracleappshelpDB

Command to select the created database oracleappshelpDB

db
oracleappshelpDB

Command to get the list of all database in the MongoDB

show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

The created database oracleappshelpDB is not listed as we need to have atleast 1 document to be inserted

db.movie.insert({"name":"oracleappshelp.com MongoDB Create Database Tutorial"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin             0.000GB
config            0.000GB
local             0.000GB
oracleappshelpDB  0.000GB

Drop Database statement in MongoDB

The below given command can be used for dropping the database from MongoDB

db.dropDatabase() 

As we are using oracleappshelpDB and inserted the document , thus current database in selection is oracleappshelpDB . If we execute the command db.dropDatabase() it will remove the database. In case of no specified database, the command will delete the default database “test”.

Execute the show dbs and use oracleappshelpDB command to switch to the required database which needs to be dropped.

show dbs
admin             0.000GB
config            0.000GB
local             0.000GB
oracleappshelpDB  0.000GB
> use oracleappshelpDB
switched to db oracleappshelpDB

Now, execute db.dropDatabase() command and then show dbs to ensure database is not shown now

> db.dropDatabase()
{ "dropped" : "oracleappshelpDB", "ok" : 1 }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB