How to create a database in MongoDB and insert data

Introduction :

Database is used in MongoDB to store all different types of collections and each collection stores documents. We will come to this later, but before that let’s learn how to create a database and how to move between databases.

Creating and moving between databases :

First of all, open your mongo shell and type and press enter for the following command :

show dbs

It will print out the list of all databases available in your system. Like below :

MY_DATABASE  0.000GB
admin        0.000GB
config       0.000GB
local        0.000GB

Now, suppose you want to create one new database. In MongoDB, we don’t have any separate command to create and switch to a database. You need to use USE DATABASE_NAME to create and switch to a database. For example, suppose you want to create one new database Users, use the following command :

> use Users
switched to db Users

It will create one new database Users if it doesn’t exist and switch to it.
To switch to a different database, use the same use command. The below image shows you how to create a database and switch to it :

mongodb create database

You can see that the last show dbs is not showing the new databases created. Because it shows only non-empty databases. So, we need to add at least one collection to our databases to make it visible.

Creating collection and document :

We can create a collection inside a database using insert method. It takes one document as the parameter. Documents are key-value pairs that we store in a database. The insert method looks like below :

db.DATABASE_NAME.insert({
	//key-value pairs 
})

For example, if we want to create a collection in the Users database, we can do it like below :

db.Users.insert(
	{
		"id" : 1,
		"name" : "Albert"
	}
)

It will give one output to inform you that one result is inserted to the database. Now, if you try to print all database name, it will show you Users database with the list.

MongoDB database create database

 

Conclusion :

In this tutorial, we have learnt how to create a database and insert simple data in MongoDB. Go through the examples and try to run them on your machine. If you have any queries and anything you want to add, drop a comment below. Happy coding 🙂

Leave a Reply