MongoDB Create Database
MongoDB is one of the most popular NoSQL databases. A NoSQL database does not use tables for storing data, instead, it uses multiple ways for storing data. These ways include key-value, document-based, and column-based. MongoDB is a document-based NoSQL database. In this article, we will discuss using MongoDB to create a database.
Create a database in MongoDB
So let’s start by running MongoDB. By default, MongoDB is installed in the C drive. Open a terminal and go to the following directory.
Note: 4.2 is the version installed in my machine. It can vary.
Run the “mongod” command.
Now, we can run the mongo shell. Open another terminal but do not close the terminal where mongod command is running. In the new terminal, type the ‘mongo’ command.
Before moving further, let’s see is there any database present. We can use the “show dbs” command for that.
There are two databases – admin and config. These two are default MongoDB databases. We will create a new database. It is very simple. The syntax to create a database in MongoDB is as follows.
Yes, just write the name of the database after “use”. Let’s do it.
Here, the name of the database is “menu”. Now, we are switched to this new database. Let’s run the show dbs command.
It does not show the database we created. It is still showing that there are only default databases. But why? We just created a database. This happens because we have not inserted any data in the newly created database. MongoDB won’t show the database on the list until we insert at least a single document in it. So let’s insert one in the menu database.
As mentioned earlier, MongoDB is a document-based database. Every MongoDB database contains collections and each collection contains documents. So we will insert a single document in a collection. MongoDB stores data in BSON format. BSON is nothing but an extension of the JSON format that supports additional data types. Observe the following document.
"dish" : "Oats with berries",
"price" : "5"
So we have a database and a document. Let’s insert this document into a collection. Let’s name this collection as “breakfast”. There are a couple of ways to create a collection. We will go for the simple one.
dish: "Oats with berries",
Observe the above command. We used the insert() method to insert the document in the “breakfast” collection. This will automatically create a collection. Let’s run this command in the mongo shell.
One document inserted successfully! Let’s again run show dbs command.
We can see it is showing the menu database in the list.
So this is how we create a database in MongoDB. It is very simple. We only have to use the “use” command. Further, we can use the “show dbs” command to see the list of databases. But remember, the list will contain the newly created database only if it has at least a single document.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.Get Started