Create Database

To create a database in MongoDB, we typically don't need to explicitly create one. MongoDB creates a database when we first store data in that database.

However, we can switch to a specific database or create one using the following steps:

Connect to MongoDB Instance:

Before creating a database in MongoDB, First, we need to connect to our MongoDB instance using the MongoDB shell or a MongoDB client library using our programming language.

By using the mongo shell, we can connect to a MongoDB server running on localhost by simply typing `mongo` command in our terminal.

Example:

mongo

Example:

show dbs

Once our connection is established successfully, we can check databases in MongoDB using the below command:

Output:

>show dbs

admin     280.00 KiB
local      65.19 GiB

Create or Switch Database:

Databases in MongoDB are created implicitly when we first store data in a database. However, if we want to explicitly switch to a specific database or create one if it doesn't exist, we can use the `use` command with `db_name`:

Example:

use your_database_name

Note: Replace "your_database_name" with the name you want for your database.

if you run the command `show dbs` it won't display the database in the list, but you can switch between databases because it was getting created explicitly.

Verify Creation:

We can verify that the database has been created by inserting some data into a collection within that database.

MongoDB will create the database if it doesn't already exist.

Example:

# Connect to MongoDB (assuming it's running locally on the default port)
> mongo

# Switch to the desired database
> use your_database_name

# Verify that you are now using the specified database
> db

This will switch a database named "your_database_name".

Note: until we insert data into a collection within a database, the database itself won't be created physically.

Adding data into Collection:

Example:

db.employees.insertOne({
    name: "Alice Collin",
    age: 20,
    department: "HR"
})

Once we have switched to the desired database, now we can start adding data to it. MongoDB is schema-less, meaning we don't need to define a schema before adding data. We can simply start inserting documents into collections within the database.

Lets assume you want to create a collection(table) called `employee` and insert a document into it:

The above command will create the `employees` collection within your database name `your_database_name` and insert the specified document(RECORD) into it.

Check Collections in MongoDB:

show collections;

Output:

employees

Note:

This approach provides flexibility and simplicity. Additionally, Creating a database in MongoDB involves connecting to the server, and then adding data to it through collections. MongoDB's schema-less nature simplifies the heterogeneous data storage within the same collection.