0% found this document useful (0 votes)
94 views21 pages

Mongo DB

MongoDB is a document-oriented NoSQL database that stores data in flexible JSON-like documents. It was created in 2007 by Dwight Merriman, Eliot Horowitz, and Kevin Ryan to provide scalability solutions. MongoDB uses dynamic schemas and is horizontally scalable by allowing data to be split across multiple servers to improve performance.

Uploaded by

Amrit Ranabhat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
94 views21 pages

Mongo DB

MongoDB is a document-oriented NoSQL database that stores data in flexible JSON-like documents. It was created in 2007 by Dwight Merriman, Eliot Horowitz, and Kevin Ryan to provide scalability solutions. MongoDB uses dynamic schemas and is horizontally scalable by allowing data to be split across multiple servers to improve performance.

Uploaded by

Amrit Ranabhat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

MONGODB

MongoDB
MongoDB is a document-oriented NoSQL database used for high-volume data storage. It
contains the data model, which allows you to represent hierarchical relationships. It uses JSON-
like documents with optional schema instead of using tables and rows in traditional relational
databases. Documents containing key-value pairs are the basic units of data in MongoDB.

History

Dwight Merriman, Eliot Horowitz, and Kevin Ryan created MongoDB in 2007. To provide a
solution for the problems of scalability and agility that they were facing at DoubleClick, they
decided to develop a database. That’s when MongoDB came into existence.

• MongoDB was first developed by 10gen Software in 2007 as part of a proposed


platform as a service solution.

• The firm switched to an open-source development approach in 2009, with commercial


support and additional services available.

• MongoDB Inc. replaced 10gen as the company’s name in 2013.

• MongoDB2.4.9 was the latest and stable version which was released on January 10,
2014.

• It became a publicly traded business on October 20, 2017, when it was listed on
NASDAQ as MDB with an IPO price of $24 per share.

• It announced a partnership with Alibaba Cloud on October 30, 2019, to provide a


MongoDB-as-a-Service solution to its clients. Customers can access BABA’s managed
services from any of the company’s worldwide data centers.

Features of MongoDB

1. Document-oriented – Since MongoDB is a NoSQL type database, instead of having


data in a relational type format, it stores the data in documents. This makes MongoDB
very flexible and adaptable to real business world situation and requirements.

2. Ad hoc queries – MongoDB supports searching by field, range queries, and regular
expression searches. Queries can be made to return specific fields within documents.

3. Indexing – Indexes can be created to improve the performance of searches within


MongoDB. Any field in a MongoDB document can be indexed.

PREPARED BY SHOBHA RANI BR 1


MONGODB

4. Replication – MongoDB can provide high availability with replica sets. A replica set
consists of two or more mongo DB instances. Each replica set member may act in the
role of the primary or secondary replica at any time. The primary replica is the main
server which interacts with the client and performs all the read/write operations. The
Secondary replicas maintain a copy of the data of the primary using built-in replication.
When a primary replica fails, the replica set automatically switches over to the
secondary and then it becomes the primary server.

5. Load balancing – MongoDB uses the concept of sharding to scale horizontally by


splitting data across multiple MongoDB instances. MongoDB can run over multiple
servers, balancing the load and/or duplicating data to keep the system up and running
in case of hardware failure.

6. Easy to use

MongoDB is a document-oriented database. It uses the concept of the document to store


data, which is more flexible than the row concept in the relational database management
system (RDBMS). A document allows you to represent complex hierarchical
relationships with a single record. MongoDB doesn’t require predefined schemas that
allow you to add to or remove fields from documents more quickly.

7. Designed to scale out

When the database grows, the challenge is to how to scale it. There are two common
ways:

• Scaling up – upgrade the current server to a bigger one with more resources (CPU,
RAM, etc). However, getting a bigger server means increasing more costs.

• Scaling out – purchase additional servers and add them to the cluster. This is cheaper
and more scalable than scaling up. The downside is that it takes more effort to manage
multiple servers than a big one.

MongoDB was designed to scale out.

MongoDB allows you to split data across many servers. It also automatically manages
the load balancing across the cluster, redistributing data, and routing updates to the
correct servers.

PREPARED BY SHOBHA RANI BR 2


MONGODB

The following picture illustrates how MongoDB scale-out using sharding across
multiple servers:

8. Rich features

Like any database system, MongoDB allows you to insert, update, and delete, and select
data. In addition, it supports other features including:

• Indexing

• Aggregation

• Specify collection and index types

• File Storage

9. High performance

MongoDB was designed to maintain the high performance from both architecture and
feature perspectives.

The philosophy of MongoDB is to create a full-featured database that is scalable,


flexible, and fast.

PREPARED BY SHOBHA RANI BR 3


MONGODB

Difference between RDBMS and MongoDB:

RDBMS MongoDB

It is a non-relational and document-oriented


It is a relational database. database.

Not suitable for hierarchical data storage. Suitable for hierarchical data storage.

It is horizontally scalable i.e we can add more


It is vertically scalable i.e increasing RAM. servers.

It has a predefined schema. It has a dynamic schema.

It is quite vulnerable to SQL injection. It is not affected by SQL injection.

It centers around ACID properties It centers around the CAP theorem


(Atomicity, Consistency, Isolation, and (Consistency, Availability, and Partition
Durability). tolerance).

It is row-based. It is document-based.

It is slower in comparison with MongoDB. It is almost 100 times faster than RDBMS.

Supports complex joins. No support for complex joins.

It is column-based. It is field-based.

It does not provide JavaScript client for


querying. It provides a JavaScript client for querying.

It supports JSON query language along with


It supports SQL query language only. SQL.

The architecture of MongoDB - NoSQL Database

MongoDB architecture is built on collections and documents. The basic unit of data in this
database consists of a set of key-value pairs. It allows documents to have different fields and
structures. This database uses a document storage format called BSON which is a binary style
of JSON documents.

PREPARED BY SHOBHA RANI BR 4


MONGODB

The following are the components of MongoDB architecture:

• Database

• Collection

• Document

Database

It is also called the physical container for data. Every database has its own set of files existing
on the file system. In a single MongoDB server, there are multiple databases present.

Collection

The collection consists of various documents from different fields. All the collections reside
within one database. In collections no schemas are present.

Document

The set of key values are assigned to the document which is in turn associated with dynamic
schemas. The benefit of using these schemas is that a document may not have to possess the
same fields whereas they can have different data types.

PREPARED BY SHOBHA RANI BR 5


MONGODB

DATA FORMATS

How is the data in a MongoDB database stored on disk?

JSON

JSON stands for JavaScript Object Notation. JSON syntax is based on a subset of JavaScript
ECMA-262 3rd edition.

A JSON document is a collection of fields and values in a structured format.

JSON is JavaScript Object Notation. It is a light-weight data interchange format, which can get
transferred from one system to the other easily. It is easy to read and write this format. It is also
not a complex task for machines to parse and generate. The text format is completely language
independent.

At high level, JSON will have two things- An object and an array. An object is a collection of
name/value pairs and an array is an ordered list of values.With the combination of two, you
can have a complete JSON structure. The maximum amount of documents that one can embed
in a document is 100. This is a very important factor while working with MongoDB.

So an object will start with curly braces and end with curly braces and then comes the key and
value. An array will start with the normal, non-curly brackets, then comes value and comma.
There are data types that can be supported. See the image below to understand it better.

"first_name": "Hasini",

"last_name": "Krishna",

"age": 22,

"skills": ["Programming","Databases", "API"]

BSON

BSON is nothing but Binary JSON i.e Binary JavaScript Object Notation. Unlike JSON, it is
not in a readable format. It supports the embedding of documents and arrays within other
documents and arrays. Like JSON, it is easy for machines to parse and generate. When you
check the websites for information, you will see the difference in JSON and BSON and
understand how different the two are in terms of readability.

PREPARED BY SHOBHA RANI BR 6


MONGODB

MONGODB Data Types

MongoDB stores documents in BSON, which is the binary encoded format of JSON. Basically,
the name BSON itself comes from Binary encoded JSON. The BSON data format provides
various types, used when we store the JavaScript objects in the binary form.

We can make remote procedure calls in MongoDB by using BSON. All the BSON data-types
are supported in MongoDB. Below are the enlisted MongoDB data types. Each MongoDB
datatypes corresponds a unique number which is used to identify them in $type method.

1) Integer

Integer is a data type that is used for storing a numerical value, i.e., integers as can save in other
programming languages. 32 bit or 64-bit integers are supported, which depends on the server.

Example:

{
"emp_name": "Shobha",
"emp_dept": "MCA",
"emp_id": 1,
}
emp_id is of the type integer since it stores a numeric number.

2) Double

Numeric numbers containing 8 bytes (64-bit IEEE 754 floating point) floating-point are stored
using the double data type. An example of a document with a double value in the field intern
score is shown below.

{
"emp_name": "Shobha",
"emp_dept": "MCA",
"emp_salary": 37500.56,
}
emp_salary is of the type double since it stores a numeric number.
PREPARED BY SHOBHA RANI BR 7
MONGODB

3) Boolean

Boolean (true or false) values are stored with the boolean data type. The field intern status is
of the type boolean in the example below because it stores the value true. Booleans take up less
space than integers or strings and avoid unwanted comparison side effects.

{
"emp_name": "Shobha",
"emp_status”: “true”,
"emp_salary": 37500.56,
}
emp_status is of the type Boolean.

4) String

This is the most commonly used MongoDB data types, BSON strings are UTF-8. Drivers for
each programming language convert from the string format of the language to UTF-8 while
serializing and de-serializing BSON.

This makes possible to easily store most international characters in BSON strings. The string
must be valid to be saved.

{
"emp_name": "Shobha",
"emp_dept”: “MCA”,
"emp_salary": 37500.56,
}
emp_name & emp_dept are of the type String.

5) Array

MongoDB data types stores array. A set of values are represented as an array. This data type
can store multiples of values and data types.

{
"emp_name": "Shobha",
"emp_skills”: [“React”,”Python”,”R”]
"emp_salary": 37500.56,
}
emp_skills is of an array type

6) Date

Date data type stores current date or time. There are various methods to return date. It can
be either as a string or as a date object. In the below table, we have discussed the methods
for the date.

PREPARED BY SHOBHA RANI BR 8


MONGODB

Date Method Description

Date() -It returns the current date in string format.

New Date() -Returns a date object. Uses the ISODate() wrapper.

ISODate() -It also returns a date object. Uses the ISODate() wrapper.

Example:

{
"emp_name": "Shobha",
"emp_skills”: [“React”,”Python”,”R”]
“emp_DOJ” : ISODate(“2001-09-27 T10:30:18.345Z)
}
7) Null

The NULL data type is used to represent a value of zero or no value, as the name implies.

{
"emp_name": "Shobha",
"emp_skills”: [“React”,” Python”,” R”],
“emp_award”: null
}
8) Object ID

An embedded document is a key-value pair that is put inside another document. Embedded
documents are stored using the object data type.

{
"emp_name": "Shobha",
"emp_dept”: {
“dept”: “MCA”,
“Semester”: 3,
“Subject”: “Machine Learning:
}
}

PREPARED BY SHOBHA RANI BR 9


MONGODB

Data Modeling in MongoDB

In MongoDB, data has a flexible schema. It is totally different from SQL database where you
had to determine and declare a table's schema before inserting data. MongoDB collections do
not enforce document structure.

The main challenge in data modeling is balancing the need of the application, the performance
characteristics of the database engine, and the data retrieval patterns.

The key challenge in MongoDB data modeling is balancing the requirements of the application.
Also, we need to assure the performance aspect effectively while modeling. Let’s point out
some requirements while MongoDB Data Modeling taking place.

1. Design schema according to the need.

2. Objects which are queried together should be contained in one document.

3. Consider the frequent use cases.

4. Do complex aggregation in the schema.

The following aspects should consider for MongoDB Data Modeling.

a. Data Usage

While designing a data model, one must consider that how applications will access the
database. Also, what will be the pattern of data, such as reading, writing, updating, and deletion
of data. Some applications are read centric and some are write-centric.

There are possibilities that some data use frequently whereas some data is completely static.
We should consider these patterns while designing the schema.

b. Document growth

Some updates increase the size of the documents. During initialization, MongoDB assigns a
fixed document size. While using embedded documents, we must analyze if the sub object can
grow further out of bounds.

Otherwise, there may occur performance degradation when the size of the document crosses
its limit. MongoDB relocates the document on disk if the document size exceeds the allocated
space for that document.

c. Atomicity

PREPARED BY SHOBHA RANI BR 10


MONGODB

Atomicity in contrast to the database means operations must fail or succeed as a single unit. If
a parent transaction has many sub-operations, it will fail even if a single operation fails.
Operations in MongoDB happen at the document level.

No single write operation can affect more than one collection. Even if it tries to affect multiple
collections, these will treat as separate operations. A single write operation can insert or update
the data for an entity. Hence, this facilitates atomic write operations.

However, schemas that provide atomicity in write operations may limit the applications to use
the data. It may also limit the ways to modify applications. This consideration describes the
challenge that comes in a way of data modeling for flexibility.

MongoDB Document Structure

There can be two ways to establish relationships between the data in MongoDB:

• Referenced Documents

• Embedded Documents

MongoDB Document Structure

a. Referenced Documents

Reference is one of the tools that store the relationship between data by including links from
one data to another. In such data, a reference to the data of one collection will be used to collect
the data between the collections.
We can say, applications resolve these references to access the related data. These are
normalized data models.
Reference relationships should be used to establish one to many or many to many relationships
between documents. Also, when the referenced entities are frequently updated or grow
indefinitely.

PREPARED BY SHOBHA RANI BR 11


MONGODB

b. Embedded Documents

These can be considered as de-normalized data models. As the name suggests, embedded
documents create relationships between data by storing related data in a single document
structure. These data models allow applications to retrieve and manipulate related data in a
single database operation.

Embedded documents should be considered when the embedded entity is an integral part of the
document and not updated frequently. It should be used when there is a contained relation
between entities and they should not grow indefinitely.

Here, in MongoDB you don't need to create a database manually because MongoDB will create
it automatically when you save the value into the defined collection at first time. It don't need
to mention what you want to create, it will be automatically created at the time you save the
value into the defined collection.

PREPARED BY SHOBHA RANI BR 12


MONGODB

Creating a Database

To create a database in MongoDB, start by creating a MongoClient object, then specify a


connection URL with the correct ip address and the name of the database you want to create.

If there is no existing database, the following command is used to create a new database.

Using Mongo Shell

A number of databases can be run on a single MongoDB server. Default database of MongoDB
is 'db', which is stored within data folder.

MongoDB can create databases on the fly. It is not required to create a database before you
start working with it.

"show dbs" command provides you with a list of all the databases.

Run 'db' command to refer to the current database object or connection.

To connect to a particular database, run use command.

In the above command, 'student' is the database we want to select.

Using NodeJS

Program to create Database

creatDB.js

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/employeDB";
PREPARED BY SHOBHA RANI BR 13
MONGODB

MongoClient.connect(url, function(err, db) {


if (err) throw err;
console.log("Database created!");
db.close();
});

Open Visual Studio Code and Run:

>node test.js

Database created!

Collection in MongoDB

A collection in MongoDB is a group of documents. Collection in MongoDB is similar to


Table in SQL relational database. Collection in MongoDB is a basic building block, which
holds the same group of documents. MongoDB stores data records as documents (specifically
BSON documents) which are gathered together in collections. A database stores one or
more collections of documents.

Program to create Collection to Database

creatcollection.js

// URL at which MongoDB service is running


var url = "mongodb://localhost:27017/";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("employeDB");
//To create collection(table) in the database (employeedb)
dbo.createCollection("employe", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});

Open Visual Studio Code and Run:

>node creatcollection.js

Collection created!

PREPARED BY SHOBHA RANI BR 14


MONGODB

Creation of Collections Using MongoDB Shell:

Step 1: Select a MongoDB database you like to Create a Collection within, using USE
command. Following is the syntax of USE command.
use <database_name>

Step 2: Insert a record to Collection, with Collection Name mentioned in the command as
shown below
db.<collection_name>.insert(<document>)
The collection should be created.

Step 3: View the existing collections using following command.


show collections

Example 1 – Create a MongoDB Collection

Following is an example where we shall try creating a collection named students in


department database.

Open Mongo Shell and follow the commands in sequence.


> use department
switched to db department
> show collections
> db.students.insert({ name: "Hasini", dept:”CSE” })
WriteResult({ "nInserted" : 1 })
> show collections
students
Following is the explanation for each mongodb command we executed above
1. use department switched to department database.
2. show collections lists the collections in the selected database. There are no collections
at this moment.
3. db.students.insert() makes a check if the collection is present. As collection is not
present yet, it creates one with the name students specified in the command.
4. show collections now lists students collection.

Explicitly Create Collection

To create a new collection in MongoDB explicitly, follow below steps :


Step 1: Select a MongoDB database you like to Create a Collection within, using USE
command. Following is the syntax of USE command.
use <database_name>

Following is the syntax of createCollection() command that creates a new collection.


db.createCollection(name, options)

PREPARED BY SHOBHA RANI BR 15


MONGODB

where
name [mandatory] name of collection

options [optional] mongodb document specifying information about collection


Options
Field Type Description

If true then collection is limited in size. i.e., Number of


capped Boolean documents that could be stored in the collection is
limited.

autoIndexId Boolean [depreciated]

size Number Size of Collection in Bytes

Number of MongoDB Documents that could be stored


max Number
in the collection

Note#1 : All fields in Options are optional.


Note#2 : If you specify capped as true, then you should specify size.
Note#3 : When a new Document arrives Collection for insertion, size and max are the
prerequisites that are verified. If the collection comes to the threshold of any, old documents
are overwritten in a round robin fashion.

View the existing collections using following command.


show collections

Insert Single Document in a Collection using insertOne()

In MongoDB, a collection represents a table in RDBMS and a document is like a record in a


table. Learn how to insert a single document into a collection.
MongoDB provides the following methods to insert documents into a collection:

1. insertOne() - Inserts a single document into a collection.


2. insert() - Inserts one or more documents into a collection.
3. insertMany() - Insert multiple documents into a collection.

insertOne()
Use the db.<collection>.insertOne() method to insert a single document in a
collection. db points to the current database, <collection> is existing or a new collection
name.
Syntax:
db.collection.insertOne(document, [writeConcern])
Parameters:
1. document: A document to insert into the collection.

PREPARED BY SHOBHA RANI BR 16


MONGODB

2. writeConcern: Optional. A document expressing the write concern to override the


default write concern.
The following inserts a document into employees collection.
Example: insertOne()

db.employees.insertOne({
name: "Shobha",
branch: "MCA",
salary:30000
})

Output
{
acknowledged: true,
insertedId: ObjectId("616d44bea861820797edd9b0")
}
In the above example, we passed a document to the insertOne() method. Notice that we
haven't specified _id field. So, MongoDB inserts a document to a collection with the auto-
generated unique _id field. It returns an object with a boolean field acknowledged that
indicates whether the insert operation is successful or not, and insertedId field with the newly
inserted _id value.

Program to insert single document to the Collection

insertdata.js

// URL at which MongoDB service is running


var url = "mongodb://localhost:27017/";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("emplyoeedb");

var myobj1 = { _id:4,name: "Rachana", dept: "Java",salary:40000};

dbo.collection("employe").insertOne(myobj1, function(err, res) {


if (err) throw err;
console.log("1 document inserted");
//console.log("Number of documents inserted: " + res.insertedCount);
console.log("one record is found now....."+res.name + ", " + res.dept + ",
" + res.salary);
db.close();
});
});

PREPARED BY SHOBHA RANI BR 17


MONGODB

Insert Multiple Documents in a Collection using insertMany()


The db.<collection>.insertMany() inserts multiple documents into a collection. It cannot
insert a single document.
Syntax:
db.collection.insertMany(
[document1, document2, ....],
{
writeConcern: <document>,
ordered: <boolean>
}
)
Example:
db.employees.insertMany(
[
{
name: "Shobha",
branch: "MCA",
salary:30000
},
{
name: "Sudha",
branch: "Dean",
salary:50000
},
{
name: "Usha",
branch: "MBA",
salary:43000
},
])

Program to insert multiple documents to the Collection

insertdata.js

// URL at which MongoDB service is running


var url = "mongodb://localhost:27017/";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("emplyoeedb");

//var myobj1 = {_id:4,name: "Rachana", dept: "Java",salary:40000};

PREPARED BY SHOBHA RANI BR 18


MONGODB

var myobj=[
{name: "Nikhil", dept: "ME", salary:20000},
{name: "Dhanush", dept: "AE", salary:56000},
{name: "Rachana", dept: "ME", salary:36000}
];
dbo.collection("students").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});

Output:

PS C:\mongo> node insertdata.js


1 document inserted
Number of documents inserted: 3

Find Single Document from Collection using findOne()

In MongoDB, a collection represents a table in RDBMS and a document is like a record in a


table. Here you will learn how to retrieve or find a single document from a collection.
MongoDB provides two methods for finding documents from a collection:
1. findOne() - returns a the first document that matched with the specified criteria.
2. find() - returns a cursor to the selected documents that matched with the specified
criteria.
findOne()
The findOne() method returns the first document that is matched with the specified criteria.

Syntax:
db.collection.findOne(query, projection)

Parameters:
query: Optional. Specifies the criteria using query operators.
projection: Optional. Specifies the fields to include in a resulted document.
The findOne() returns the first document from a collection if no parameter is passed.

Example:

db.employees.findOne({name: "Shobha"})

The findOne() method performs the case-sensitive search, so {name:


"Shobha"})and ({name: "shobha"})returns different result.

PREPARED BY SHOBHA RANI BR 19


MONGODB

Use the query operators for more refined search. For example, the following finds the first
document where salary is greater than 40000.

db.employees.findOne({salary: {$gt: 40000}})

Output:

{
name: "Sudha",
branch: "Dean",
salary:50000
},
{
name: "Usha",
branch: "MBA",
salary:43000
}

Program to Find a single document

finddata.js
// URL at which MongoDB service is running
var url = "mongodb://localhost:27017/";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("emplyoeedb");

dbo.collection("employe").findOne({name:'Rachana'}, function(err, res) {


console.log("one record is find now....."+res.name + ", " + res.dept +
", " + res.salary);
db.close();
});

Program to Find a multiple documents with query operators

finddata.js

// URL at which MongoDB service is running


var url = "mongodb://localhost:27017/";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(err, db) {


if (err) throw err;

PREPARED BY SHOBHA RANI BR 20


MONGODB

var dbo = db.db("emplyoeedb");


dbo.collection("employe").find({salary: {$gt: 25000}}).toArray(function(err,
res) {
if (err) throw err;
for(i = 0; i < res.length; i++) {
let data = res[i];
console.log(data.name + ", " + data.dept + ", " + data.salary);
}

db.close();
});
});

Output:

PS C:\mongo> node finddata.js


Hasini, CSE, 50000
Rachana, ECE, 40000
Rachana, ECE, 40000
Rachana, Java, 40000

PREPARED BY SHOBHA RANI BR 21

You might also like