Mongodb create database command line: In MongoDB, we can manually create a collection, but creating a database is an automatic task in MongoDB. This is a distinguished feature in MongoDB, unlike the SQL databases where creating a database is a manual task.
- MongoDB Tutorial
- Advanced MongoDB
- MongoDB Useful Resources
- Selected Reading
In this chapter, we will see how to drop a database using MongoDB command.
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows −
This will delete the selected database. If you have not selected any database, then it will delete default 'test' database.
Example
First, check the list of available databases by using the command, show dbs.
If you want to delete new database <mydb>, then dropDatabase() command would be as follows −
Now check list of databases.
MongoDB didn’t provides any command to create “database“. Actually, you don’t need to create it manually, because, MangoDB will create it on the fly, during the first time you save the value into the defined collection (or table in SQL), and database.
For developer from SQL background, we need to create a database, table and insert values into table manually. In MongoDB, you don’t need to mention what you want to create, when first time you save the value into the defined collection (table), under selected database, MangoDB will create the value, collection and database automatically.
Note
MongoDB contains “
MongoDB contains “
db.createCollection()
” to create collection manually, but Not database.In this guide, we will show you how and when MongoDB will create the database and collections.
1. Show all database
Issue “
show dbs
” to display all available databases.Currently, only two databases are available – “admin” and “local“.
2. Define a database name
Issue “
use new-databasename
” to switch from default database to define database (even non-exists database name will work). However, MangoDB doesn’t create any database yet, until you save something inside.P.S Database “mkyongdb” is not created yet.
3. Save It
Define a collection named “users“, and save a dummy document(value) inside.
This says, “save this document (value) ‘
{username:'mkyong'}
‘ into the ‘user’ collection”. When this “save” operation is performed, MangoDB will create the “user” collection, and “mkyongdb” database automatically.