MongoDB Create Database


MongoDB Create Database

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.


Syntax

use database_name

The use command switches to the specified database. If the database does not exist, MongoDB will create it upon inserting data.


Example MongoDB Create Database

Let's look at some examples of creating and using a database in MongoDB:

1. Switch to a Database

use myNewDatabase

This command switches to a database named myNewDatabase. If the database does not exist, it will be created when data is inserted.

2. Insert Data to Create the Database

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.


Full Example

Let's go through a complete example that includes switching to a new database, inserting data, and verifying the database creation.

Step 1: Switch to a New Database

This step involves switching to a new database named myNewDatabase.

use myNewDatabase

In this example, we switch to the myNewDatabase database.

MongoDB Create Database

Step 2: Insert Data into the 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.

MongoDB Create Database

Step 3: Verify the Database Creation

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.

MongoDB Create Database

Conclusion

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.