1. Create Database in MongoDB
It’s strange to listen but true that MongoDB doesn’t provide any command to create databases. Then the question is how would we create database ?. The answer is – We don’t create database in MongoDB, we just need to use database with your preferred name and need to save a single record in database to create it.
List Databases – First check the current databases in our system.
# mongo> show dbs;
admin (empty)local 0.078GBtest 0.078GB
Use New Database –
Now if we want to create database with name exampledb. Just run following command and save a single record in database. After saving your first example, you will see that new database has been created.> use exampledb;> s = { Name : "TecAdmin.net" }> db.testData.insert( s );
List Databases –
Now if you list the databases, you will see the new database will be their with name exampledb.> show dbs;
admin (empty)local 0.078GBexampledb 0.078GBtest 0.078GB
2. Drop Database in MongoDB
MongoDB provides dropDatabase() command to drop currently used database with their associated data files. Before deleting make sure what database are you selected using db command.
> db
exampledb
Now if you execute dropDatabase() command. It will remove exampledb database.
> db.dropDatabase();
{ "dropped" : "exampledb", "ok" : 1 }
To delete MongoDB database from Linux command line or Shell Script – Use following command from
# mongo exampledb --eval "db.dropDatabase()"