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:
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.
mongo
Once our connection is established successfully, we can check databases in MongoDB using the below command:
show dbs
>show dbs admin 280.00 KiB local 65.19 GiB
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` keyword with `your_database_name`.
use your_database_name
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.
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.
This will switch to a database named "your_database_name".
# 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
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.
Let's assume you want to create a collection or table called `employee` and insert a document into it.
db.employee.insertOne({ name: "Alice Collin", age: 20, department: "HR" })
The above command will create the `employee` collection within your database name `your_database_name` and insert the specified document or RECORD into it.
show collections;
employee
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.