Database Create and Drop
In this lesson we will learn how to create and drop a Database in MongoDB.
Creating a Database
Open the command prompt and navigate to the /bin folder of the MongoDB using the
cd
command and execute the command mongod
there. This will initiate the MongoDB server. We have to keep this command prompt window alive, as this is running MongoDB. To stop the MongoDB server, simply enter exit
and press Enter.
Now, Open another command prompt and navigate to the /bin folder of the MongoDB again and execute the command
mongo
. This will open up the client to run the MongoDB commands.
In the command prompt window in which we ran the
mongo
command, after successfully connecting to the mongodb, just type the command the following :use database_name
This will create a new database with the name database_name if there is no database already present with the same name. If a database already exists with the mentioned name, then it just connects to that database.
In the above picture, it creates a new database called mynewdatabase and will also connect to the same.
To check the current connected database, type in
db
in the command prompt window, and you will get the name of the current database as result.
To see the list of all the databases in MongoDB, use command
show dbs
Please note that the newly created dstabase mynewdatabase has not been listed after running the above command. This is because, no records have been inserted into that database yet. Just insert one record and then run the command again as shown below :
To Insert data, run the following command. Dont worry about it, we will learn this in detail in next lessons.
db.student.insert({ name : "Viraj" })
NOTE : In MongoDB,
test
will be the default database. If no database is created, then all the data will be stored in the test
database.Drop a Database
First check the list of databases available as shown below, using the
show dbs
command.
If the newly created database mynewdatabase has to be dropped(deleted). Run the below command to delete the database. Before deleting the database, connect to the required database which is to be deleted.
db.dropDatabase()
Now again check the list of databases, to verify whether the database is deleted or not.
Note that the database mynewdatabase has been deleted and hence, it will not be listed in the list of the databases.
No comments:
Post a Comment