NoSQL Database

Unleash the power of NoSQL Database – MongoDB

Abstract
This article’s targeted audience is, mostly, developers who want a quick start with a
NoSQL database like MongoDB. The article explains the usefulness of a NoSQL database over a SQL database.

Introduction

What is MongoDB?

MongoDB is classified as NoSQL Databases, developed by MongoDB Inc.

It was initially released in February 2009, mainly Written in C++, Go, JavaScript and Python.

It’s a cross-platform document-oriented database program. MongoDB uses a JSON-like document for the schema. Like Tables in SQL database, we use a collection to store the document in MongoDB.

Let’s go through the basic of MongoDB before taking a deep dive into it.

What are Collections in a MongoDB database?

A collection of a MongoDB database is equivalent to a table of a (Relational database Management system)RDBMS. It can store several documents. It’s not necessary to keep the same structure of the document; we can vary the fields according to our needs. MongoDB is a schema-less database, which means you don’t have to define the number of columns with their datatype as SQL table requires.

What are documents in a MongoDB database?

A document is a unit of storing data in a MongoDB collection. It’s equivalent to a record/row of an RDBMS table (SQL table).Document use JSON (JavaScript Object Notation) style for storing data. It’s a lightweight object which is used to interchange data between various applications.

Following are the example of documents in a User’s collection.

[ {
‘_id’ : 1,
‘name’ : { ‘first’ : ‘shiv’, ‘last’ : ‘singh’ },
‘Email’:{
‘primary’:’pratapshiv1992@gmail.com’,
‘secondary’:’shiv123@gmail.com’ }
},
{
‘_id’ : 2,
‘name’ : { ‘first’ : ‘Subodh’, ‘last’ : ‘Tondon’ },
}]

MongoDB stores data in a flexible manner, fields can vary document to document (as we have seen in above example), It means we can have a schema-less database which we can be changed after a while, according to the changed requirements.

Indexing queries and real-time aggregation are powerful ways to access and analyze your data. MongoDB is free to use. Prior October 16, 2018, Released Versions of MongoDB are published under the AGPL and after October 16, 2018, are published under the Server-Side Public License (SSPL).

Concepts and Terminology translation :

If you are only familiar with SQL Database, not MongoDB, then we have a quick translation cheat sheet for you.

Why and When MongoDB?

Well, it’s a good question, many of us ignore the basic difference of both types of database and sometimes go with the wrong implementation. We will talk about a real-world problem which can be solved in a better way with a NoSQL database instead of SQL Database.

Let’s suppose, we are saving records for the users. A user may have a single phone number and a single email but at the same time, another user may have multiple emails and phone numbers. If we are using a NoSQL database we can create any number of field in the document. We know that a document may have any number of field it needs.

Let’s take it to the next level, suppose in future, the requirements have been changed and we want to store few more additional information of users like address, Aadhar number, pan number, etc. Now if we are using the SQL database then we must revise our schema but if we have NoSQL database like MongoDB, we can fulfill the requirements with no changes at all because a document may have any number of fields it needs. When we are dealing with unstructured data, it’s good to go with NoSQL database.

Now we know enough about the MongoDB, it’s time to code and have some real implementation of MongoDB.

Installation:

Go to below link:

  • https://docs.mongodb.com/manual/installation/?_ga=2.149530550.1043787721.1561815631-456153019.1561815631
  • Select “MongoDB Community Edition Installation Tutorials” under the “Installation MongoDB” section.
  • If you have a Linux operating system, then select your Linux distribution. Like if you have ubuntu system, click “Install MongoDB Community Edition on Ubuntu”.
  • For window click “Install MongoDB Community Edition on Windows”
  • For macOS click ” Install MongoDB Community Edition on macOS”
  • Open the terminal (Ctrl + Alt) and run the below command for install the dependencies for Ubuntu 18.04 (Bionic).
  • sudo apt-get install libcurl4 openssl
  • Download the MongoDB .tgz tarball from the below link
  • “https://www.mongodb.com/download-center/community?jmp=docs” and select package “TGZ” and press the download button.
  • Go to the download directory and open a terminal and run the below command to extract the downloaded file.
  • tar -zxvf mongodb-linux-*-4.0.10.tgz
  • export PATH=<mongodb-install-directory>/bin:$PATH
  • Replace <mongodb-install-directory> with the path to the extracted MongoDB archive.

Create the data and log directories:

Create a directory where the MongoDB instance stores its data. Use the below command
sudomkdir -p /data/db

Now we need to create a directory where MongoDB instance stores its log. Run the below command
sudomkdir -p /var/log/mongodb

To run the MongoDB run the following command

sudomongod –dbpath /data/db –logpath /var/log/mongodb/mongod.log –fork

To check MongoDB has started successfully or not go to /var/log/mongodb/mongod.log. You will see the message “[initandlisten] waiting for connections on port 27017” in the file

Using the MongoDB.

Run the command – mongo, the below is the response.
CRUD (create,read,update,delete) operations

Create Database:

MongoDB provides a command to create DB as follow

I/P: use Demo
O/P: switched to DB Demo

Where Demo is a database. If this exists MongoDB will switch to Demo database but if it doesn’t exist, then it will create it and then switch to Demo database

Create a Document:

By using the below command, we can create a new document
db.users.insertOne()
db.users.insertMany()

where DB is an instance of database and users is the collection name, in which , all the documents related to user will be created

For Exp:

db.users.insertOne({
name: “subodh”,
email: “subodh.tandon@gmail.com”,
phone: “8447300000”
})

and will get the following response

/* 1 */
{
“acknowledged”: true,
“insertedId”: ObjectId(“5d189a631f8c7b96c4d5ec2e”)
}

Insert many records

db.users.insertMany([
{
name: “Shiv”,
email: “shivpratapsingh@gmail.com”,
phone: “7777777777”
},
{
name: “Rohit”,
email: “rohit@gmail.com”,
phone: “8768123456”
}
]);

will get the below response

/* 1 */
{
“acknowledged”: true,
“insertedIds”: [
ObjectId(“5d189c971f8c7b96c4d5ec2f”),
ObjectId(“5d189c971f8c7b96c4d5ec30”)
]
}

Read Document:

Now we have to see the inserted document using the below command

db.users.find()

we get the below response

/* 1 */
{
“_id”: ObjectId(“5d189a631f8c7b96c4d5ec2e”),
“name”: “subodh”,
“email”: “subodh.tandon@gmail.com”,
“phone”: “8441234567”
}

Update Document:

Using the below command, we can update the document

db.users.updateOne()
db.users.updateMany()

Using db.users.updateOne();

Exp:

db.users.updateOne(
{“name”: “subodh”},{$set: {status: “active”}}
)

It will create the new field status and set it to active
we get the below response

/* 1 */
{
“acknowledged”: true,
“matchedCount”: 1.0,
“modifiedCount”: 1.0
}

using db.users.updateMany();

Exp:

db.users.updateMany(
{},{$set: {status: “updated many”}}
)
Here {} means no criteria is provided to update the documents. That means it will update all the documents.
we will get the below response

/* 1 */
{
“acknowledged”: true,
“matchedCount”: 3.0,
“modifiedCount”: 3.0
}

Here are the updated documents. Use db.users.find() and will get all the documents

/* 1 */
{
“_id”: ObjectId(“5d189a631f8c7b96c4d5ec2e”),
“name”: “subodh”,
“email”: “subodh.tandon@gmail.com”,
“phone”: “8447312345”,
“status”: “updated many”
}
/* 2 */
{
“_id”: ObjectId(“5d189c971f8c7b96c4d5ec2f”),
“name”: “Shiv”,
“email”: “shivpratapsingh@gmail.com”,
“phone”: “7777777777”,
“status”: “updated many”
}
/* 3 */
{
“_id”: ObjectId(“5d189c971f8c7b96c4d5ec30”),
“name”: “Rohit”,
“email”: “rohit@gmail.com”,
“phone”: “8768512345”,
“status”: “updated many”
}

Delete document:

db.users.deleteOne()

by using the above command we can delete a document

Exp:

db.users.deleteOne({name: “Rohit”
})

will get the following response

/* 1 */
{
“acknowledged”: true,
“deletedCount”: 1.0
}

Looking for a reliable web application development company for your business? QSS Technosoft is a renowned Software Development Company and has created several web apps addressing different business needs for its clients across the world. We focus on your success by creating most user-friendly web & mobile apps that are 100% result-oriented. So, don’t look around & leverage the power of most scalable web apps to promote your business!

About Author:
Author Shiv Pratap is a full stack engineer currently working with QSS Technosoft. He has worked in Node.JS, Graphql, Express.js, ReactJS, Java, Twilio, Google and Firebase cloud compute solutions. He is always ready to explore new and upcoming technologies.

Subodh Tandon is an experienced software engineer with a demonstrated history of working in the information technology and services industry. Strong engineering professional skilled in ReactJS, Redux, JavaScript, NodeJS, MongoDB, PHP, Yii2, MYSQL , JSON ,HTML and CSS.

Renovate unique Business Processes into Digitally Transformed solutions with QSS Technosoft!!

Do you want to remove manual operations, acting as impediment to your business growth? Realize your ideas into reliable web and mobile software solutions with our professional services. Take first step to launch your project by filling the form.

Let's computerize your business process


or Call Us