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
show dbs
Once our connection is established successfully, we can check databases in MongoDB using the below command:
>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` command with `db_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.
# 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".
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.
show collections;
employees
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.