Database in MongoDB

In this article, we will learn how to create database in MongoDB using MongoDB Shell or Compass.

Lets starts with MongoDB Shell first. Open Terminal or command prompt. First we have to start MongoDB Server and then MongoDB client.

Start MongoDB Server

mongod

Start MongoDB client

mongo

Mongosh

For mongoDB 6.0 and above, the default shell is Mongosh. Install Mongosh Mongosh from Mongo DB Download center.

mongosh

The default port no of MongoDB server is 27017.

MongoDB will connect to default test database.


Create Database in MongoDB

To create a new Database in MongoDB, type "use dbname".

switched to db cars

use cars

This will create a new Database cars in MongoDB.


Check Database Name

cars

db

Add data in database

Now lets add some data in cars database. For that, we have to create a collection ( i.e. maruti ) and then insert data in collection. See example

db.maruti.insert({name:"swift"});

Database in Compass

Now open MongoDB Compass. Connect using default settings.

Create Databse in MongoDB Compass
Create Database in MongoDB Compass

Show all Databases

To show all databases in MongoDB, type show dbs in MongoDB Shell.

admin 0.000GB

cars 0.000GB

config 0.000GB

local 0.000GB

show dbs

This will show all available databases


Select Database

To select a database from available list, use use dbname command.

switched to db cars

use cars

This will select cars database from database lists.