The MongoDB create database
operation is unique compared to traditional relational databases. In MongoDB, a database is created dynamically when you insert data into it. You do not need to explicitly create a database.
use database_name
The use
command switches to the specified database. If the database does not exist, MongoDB will create it upon inserting data.
Let's look at some examples of creating and using a database in MongoDB:
use myNewDatabase
This command switches to a database named myNewDatabase
. If the database does not exist, it will be created when data is inserted.
db.programGuru.insertOne({ name: "John Doe", age: 30 });
This command inserts a document into the programGuru
collection in the myNewDatabase
database. Since myNewDatabase
does not exist, MongoDB creates it dynamically.
Let's go through a complete example that includes switching to a new database, inserting data, and verifying the database creation.
This step involves switching to a new database named myNewDatabase
.
use myNewDatabase
In this example, we switch to the myNewDatabase
database.
This step involves inserting some sample data into the myNewDatabase
database.
db.programGuru.insertOne({ name: "John Doe", age: 30 });
Here, we insert a document into the programGuru
collection in the myNewDatabase
database.
This step involves listing the databases to verify that myNewDatabase
has been created.
show dbs
This command lists all databases, and you should see myNewDatabase
in the list.
The MongoDB create database
operation is simple and dynamic. By using the use
command and inserting data, MongoDB automatically creates a new database. Understanding this process is essential for working effectively with MongoDB.