MongoDB Creating a Database
Syntax
The syntax for creating a database in MongoDB is as follows:
use DATABASE_NAME
If the database does not exist, it will be created; otherwise, it will switch to the specified database.
Example
The following example demonstrates creating a database named tutorialpro:
> use tutorialpro
switched to db tutorialpro
> db
tutorialpro
>
To view all databases, you can use the show dbs command:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
>
As you can see, the newly created database tutorialpro is not listed among the databases. To display it, we need to insert some data into the tutorialpro database.
> db.tutorialpro.insert({"name":"tutorialpro.org"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
tutorialpro 0.000GB
The default database in MongoDB is test. If you do not create a new database, collections will be stored in the test database.
Note: In MongoDB, a collection is only created after inserting content! This means that after creating a collection (table), you need to insert a document (record) for the collection to be actually created.