How to create a database using MongoDB and implement the basic CRUD operations?

This blog gives a brief introduction to MongoDB and contains step by step instructions to install MongoDB and implement the basic CRUD operations on a database

Initially, before discussing about MongoDB lets see what is MongoDB?

MongoDB is a NoSQL document database which means it stores data in JSON like documents. It has a powerful query language.

How to install MongoDB?

Step 1: Go to www.mongodb.com

Step 2: After it is loaded go to –

Software -> Community Server -> Select the platform -> Select the package as ‘msi’ -> Click Download

Step 3: After the download is completed double click on the setup

Step 4: Once the installer starts, click ‘Next’

Step 5: Accept the Terms and Agreement and Click Next

Step 6: Choose Complete installation and click Next

Step 7: Select ‘Install MongoD as a Service’ and choose ‘Run service as Network Service user’. The Data Directory is the location where MongoDB will be installed. Keep it as the default. Better not to change it.

Step 9: Click Next and finally Click ‘Install’

Now it will start the installation and once the installation has been completed, click Finish.

Setting Up MongoDB

Initially, we need to set up the data folder where MongoDB will store our databases. So, create a new folder called data inside Local Disk(C) and inside this data folder create a new folder named db.

Next, we need to create 2 shortcuts to access mongo.exe and mongod.exe directly from the terminal using keywords instead of typing the location every time.

So to do this follow the below steps.

Step 1: Open the terminal

Step 2: Go to the root directory. If you are already in the root directory you can skip this step.

Step 3: Create a new hidden file named bash_profile using the below command :
touch .bash_profile

Step 4: Open this file using the vim editor using the below command: vim .bash_profile

Step 5: Press i to insert

Step 6: Next we need to assign the location of mongo.exe and mongod.exe to 2 variables. To do this enter the following commands in the vim editor.

alias mongod = “/C/Program\ files/MongoDB/Server/4.2/bin/mongod.exe”
alias mongo = “/C/Program\ files/MongoDB/Server/4.2/bin/mongo.exe”

Note: You should mention the proper version you have installed when mentioning the path.

Step 7: Now press Esc and enter ‘:wq’ to save and exit the vim editor

Step 8: Next we can check whether MongoDB has been set up properly by entering the following command in the terminal

mongo — version

If you see the version of MongoDB and other related details. Congratulations! You have successfully set up MongoDB.

If you get any other messages such as “Command not found” then please retry the above steps, make sure you don’t have any typos and have typed exactly the same and also make sure to check the location of mongo.exe and mongod.exe.

Creating a Database

Step 1: Start the MongoDB server, you can start the server by typing mongod in the terminal

Step 2: Open a new tab in the terminal or open a new terminal and type mongo to open the mongo shell.

Step 3: Now you can create a database by typing use dbName, where you need to specify the database name instead of dbName

For future demonstration purposes of the CRUD operations, I will create a database named shopDB using the following command
use shopDB

Note :
Some useful commands –
To view all the databases : show dbs
To view the current db : db
Deleting a db : db.dropDatabase()

CRUD Operations via the Mongo shell

All the CRUD operations are performed in the mongo shell in the terminal. So, start the MongoDB server by typing mongod in the terminal and then open a new tab in the terminal or open a new terminal and type mongo to open the mongo shell.

Inserting Data

In SQL we create tables and then we insert data but in NoSQL, we don’t create tables but we create collect Collections and insert data. So in order to demonstrate, I will create a collection named products, and then I will insert data.

You can view all the created collections by typing show collections

Note: When you are using the below codes instead of using products use the name of the collection you created.

Inserting One entry –

The data is inserted as key-value pairs

If the collection already exists then it inserts into it or else it creates a new collection and inserts into it.

Reading data

To view all the data in a collection use the command db.products.find()
This command will return the data in products collection as JSON objects.

Syntax to read data
db.collectionName.find( {Query} , { projections })

projections : The fields to display

Finding specific data from a collection

1. Find the products having the name Shoes
db.products.find({name:”Shoes”})

2. Find the products having price greater than 1500
db.products.find({price : {$gt : 1500}})

3. Find the name of the product having id = 2

Updating Data

Syntax
db.CollectionName.updateOne( { Query } , { set values })

eg: Update price of the product having id = 1 to 2000
db.products.UpdateOne({ id: 1}, { $set : { price : 2000}})

Deleting Data

Syntax
db.CollectionName.deleteOne( { Query } )

eg: Delete the product having id = 2
db.products.deleteOne( {id:2} )

3rd year Software Engineering Undergraduate