Mean Stack Technologies Unit-5 (2)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.

Umar Khan, KHIT, Guntur


Syllabus: Mongo DB: Introduction, Architecture, Features, Examples, Database Creation & Collection in Mongo
DB. Deploying Applications: Web hosting & Domains, Deployment Using Cloud Platforms.
UNIT –V
Mongo DB
(1) Introduction:
MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead of
using tables and rows as in the traditional relational databases, MongoDB makes use of collections
and documents. Documents consist of key-value pairs which are the basic unit of data in MongoDB.
Collections contain sets of documents and function which is the equivalent of relational database
tables. MongoDB is a database which came into light around the mid-2000s.
(2) Architecture:
Key Components of MongoDB Architecture
Below are a few of the common terms used in MongoDB
1. _id – This is a field required in every MongoDB document. The _id field represents a unique
value in the MongoDB document. The _id field is like the document's primary key. If you create
a new document without an _id field, MongoDB will automatically create the field. So for
example, if we see the example of the above customer table, Mongo DB will add a 24 digit
unique identifier to each document in the collection.

_Id CustomerID CustomerName OrderID

563479cc8a8a4246bd27d784 11 Guru99 111

563479cc7a8a4246bd47d784 22 Trevor Smith 222

563479cc9a8a4246bd57d784 33 Nicole 333


2. Collection – This is a grouping of MongoDB documents. A collection is the equivalent of a
table which is created in any other RDMS such as Oracle or MS SQL. A collection exists within
a single database. As seen from the introduction collections don't enforce any sort of structure.
3. Cursor – This is a pointer to the result set of a query. Clients can iterate through a cursor to
retrieve results.
4. Database – This is a container for collections like in RDMS wherein it is a container for tables.
Each database gets its own set of files on the file system. A MongoDB server can store
multiple databases.
5. Document - A record in a MongoDB collection is basically called a document. The document,
in turn, will consist of field name and values.
6. Field - A name-value pair in a document. A document has zero or more fields. Fields are
analogous to columns in relational databases.
The following diagram shows an example of Fields with Key value pairs. So in the example
below CustomerID and 11 is one of the key value pair's defined in the document.

7. JSON – This is known as JavaScript Object Notation. This is a human-readable, plain text
format for expressing structured data. JSON is currently supported in many programming
languages.
Page 1
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur
Just a quick note on the key difference between the _id field and a normal collection field. The _id
field is used to uniquely identify the documents in a collection and is automatically added by
MongoDB when the collection is created.
Why Use MongoDB?
Below are the few of the reasons as to why one should start using 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.
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.
(3) Features
MongoDB Features
1. Each database contains collections which in turn contains documents. Each document
can be different with a varying number of fields. The size and content of each document
can be different from each other.
2. The document structure is more in line with how developers construct their classes and
objects in their respective programming languages. Developers will often say that their
classes are not rows and columns but have a clear structure with key-value pairs.
3. The rows (or documents as called in MongoDB) doesn't need to have a schema defined
beforehand. Instead, the fields can be created on the fly.
4. The data model available within MongoDB allows you to represent hierarchical
relationships, to store arrays, and other more complex structures more easily.
(4) Example
MongoDB Example
The below example shows how a document can be modeled in MongoDB.
1. The _id field is added by MongoDB to uniquely identify the document in the collection.
2. What you can note is that the Order Data (OrderID, Product, and Quantity ) which in RDBMS
will normally be stored in a separate table, while in MongoDB it is actually stored as an
embedded document in the collection itself. This is one of the key differences in how data is
modeled in MongoDB.

Page 2
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur
(5) Database Creation & Collection in Mongo DB:
Method 1: Creating the Collection in MongoDB on the fly
The cool thing about MongoDB is that you need not to create collection before you insert document in
it. With a single command you can insert a document in the collection and the MongoDB creates that
collection on the fly.
Syntax: db.collection_name.insert({key:value, key:value…})

For example:
We don’t have a collection beginnersbook in the database beginnersbookdb. This command will
create the collection named “beginnersbook” on the fly and insert a document in it with the specified
key and value pairs.

> use beginnersbookdb


switched to db beginnersbookdb

db.beginnersbook.insert({
name: "Chaitanya",
age: 30,
website: "beginnersbook.com"
})
You would see this response in the command prompt.

WriteResult({ "nInserted" : 1 })

To check whether the document is successfully inserted, type the following command. It shows all the
documents in the given collection.
Syntax: db.collection_name.find()
> db.beginnersbook.find()
{ "_id" : ObjectId("59bcb8c2415346bdc68a0a66"), "name" : "Chaitanya",
"age" : 30, "website" : "beginnersbook.com" }

To check whether the collection is created successfully, use the following command.
show collections

Page 3
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur
This command shows the list of all the collections in the currently selected database.
> show collections
beginnersbook
Method 2: Creating collection with options before inserting the documents
We can also create collection before we actually insert data in it. This method provides you the
options that you can set while creating a collection.
Syntax:
db.createCollection(name, options)
name is the collection name
and options is an optional field that we can use to specify certain parameters such as size, max
number of documents etc. in the collection.
First lets see how this command is used for creating collection without any parameters:
> db.createCollection("students")
{ "ok" : 1 }

Lets see the options that we can provide while creating a collection:
capped: type: boolean.
This parameter takes only true and false. This specifies a cap on the max entries a collection can
have. Once the collection reaches that limit, it starts overwriting old entries.
The point to note here is that when you set the capped option to true you also have to specify the size
parameter.
size: type: number.
This specifies the max size of collection (capped collection) in bytes.
max: type: number.
This specifies the max number of documents a collection can hold.
autoIndexId: type: boolean
The default value of this parameter is false. If you set it true then it automatically creates index field
_id for each document. We will learn about index in the MongoDB indexing tutorial.
Lets see an example of capped collection:
db.createCollection("teachers", { capped : true, size : 9232768} )
{ "ok" : 1 }
This command will create a collection named “teachers” with the max size of 9232768 bytes. Once
this collection reaches that limit it will start overwriting old entries.

Page 4
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur
(6) Deploying Applications: Web hosting & Domains, Deployment Using Cloud Platforms

Deploy a Production-Ready MEAN Application using Bitnami MongoDB with Replication on Google
Cloud Platform
Author(s): @vikram-bitnami , Published: 2017-07-06

Google Cloud Community tutorials submitted from the community do not represent official Google
Cloud product documentation.

This tutorial demonstrates how to deploy a MEAN (MongoDB, Express, Angular and Node) Web
application with a multi-node MongoDB replica set on Google Cloud Platform using Bitnami MEAN
and Bitnami MongoDB with Replication. This approach produces a more scalable and resilient
deployment that could be used for production or mission-critical scenarios. This tutorial assumes that
you're familiar with MongoDB and MEAN applications.
Objectives
Deploy Bitnami MEAN on a Compute Engine instance.
Install and configure a sample MEAN application.
Serve the application with Apache.
Deploy Bitnami MongoDB with Replication on a set of Compute Engine instances.
Connect the MEAN application to the Bitnami MongoDB with Replication cluster.
Test service continuity (optional)
Before you begin
Before starting this tutorial, ensure that you have set up a Google Cloud Platform project. You can
use an existing project or create a new project.

Cost
The default configuration allows you to run a MEAN application using 1 f1-micro instance with a
standard 10 GB persistent disk for the application server, and 3 n1-standard-2 instances, each with a
standard 10 GB persistent disk, for the MongoDB cluster. You can customize the configuration when
deploying this solution or change it later, although the default configuration is fine for the purposes of
this tutorial.

Estimated cost for the above default configuration is $4.28 per month for the single f1-micro instance
and $148.04 per month for the three n1-standard-2 instances comprising the Bitnami MongoDB with
Replication cluster, based on 30-day, 24 hours per day usage in the us-central1 (Iowa) region.
Sustained use discount is included.

Use the pricing calculator to generate a cost estimate based on your projected usage. New Google
Cloud customers may be eligible for a free trial.

Deploy Bitnami MEAN on a Compute Engine instance


Deploy Bitnami MEAN on a Compute Engine instance:

From the Cloud Marketplace, select the MEAN Certified by Bitnami template.
Review the information and cost. Click Launch on Compute Engine to proceed.
Review the default zone, machine type, boot disk size and other parameters and modify as needed.
Ensure that the Allow HTTP traffic and Allow HTTPS traffic boxes are checked in the firewall
configuration. Click Deploy to proceed with the deployment.
The Cloud Marketplace deploys Bitnami MEAN on a new Compute Engine instance. You can monitor
the progress of the deployment from the Deployment Manager. Once deployed, note the public IP
address of the instance and the password for the MongoDB database.

Install and configure a sample MEAN application

Page 5
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur
This section uses a sample MEAN application from GitHub. If you already have a MEAN application
to deploy, you can use it instead; simply adapt the installation and configuration steps below as
needed.

Login to the deployed instance and install and configure the MEAN application:

From the Deployment Manager, click the SSH button to login to the instance over SSH.
Once logged in, switch to the bitnami user account:

sudo su - bitnami

Navigate to the default application folder:

cd /opt/bitnami/apps/

Create the folder structure for the MEAN application:

sudo mkdir myapp


sudo mkdir myapp/conf
sudo mkdir myapp/htdocs

Download the application source code into the myapp/htdocs folder:

cd myapp/htdocs
sudo git clone https://github.com/cornflourblue/mean-stack-registration-login-example.git .

Install the necessary application dependencies:

sudo npm install

Login to the MongoDB database using the mongo command-line client. Use the password obtained
from the Deployment Manager when prompted.

mongo admin --username root -p

Once logged in, create a new database and user account for the application:

use mydb
db.createUser(
{
user: "myuser",
pwd: "mypass",
roles: [ "readWrite" ]
}
)
exit

Modify the application configuration to use the new database and credentials by modifying the
/opt/bitnami/apps/myapp/htdocs/config.json file as shown below:

{
"connectionString": "mongodb://myuser:mypass@localhost:27017/mydb",
...
}

Page 6
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur
Serve the application with Apache
Express will typically serve the MEAN application on port 3000. This port is closed by default in
Bitnami MEAN for security reasons. However, Bitnami MEAN also includes the Apache Web server,
which can be configured as a reverse proxy for Express on the standard Web server port 80.

Configure Apache to work as a reverse proxy for Express and accept requests for the MEAN
application on port 80:

Create the /opt/bitnami/apps/myapp/conf/httpd-prefix.conf file and add the line below to it:

Include "/opt/bitnami/apps/myapp/conf/httpd-app.conf"

Create the /opt/bitnami/apps/myapp/conf/httpd-app.conf file and add the content below to it to enable
the reverse proxy:

ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/

Add the following line to the end of the main Apache configuration file at
/opt/bitnami/apache2/conf/bitnami/bitnami-apps-prefix.conf:

Include "/opt/bitnami/apps/myapp/conf/httpd-prefix.conf"

Restart the Apache server using the Bitnami control script:

sudo /opt/bitnami/ctlscript.sh restart apache

Start the Express server:

cd /opt/bitnami/apps/myapp/htdocs
forever start server.js

Browse to the public IP address of your Bitnami MEAN instance and confirm that you see the MEAN
example application's welcome page. Register a new user account in the example application using
the Register link and then log in to the example application by entering the new user account
credentials into the login form and clicking the Login button.

If you are able to perform the above tasks, your MEAN application is now operational, albeit using the
locally-installed MongoDB database instance. The remaining sections of this tutorial will show you
how to deploy a separate Bitnami MongoDB with Replication cluster and reconfigure the MEAN
application to use that cluster instead.

Deploy Bitnami MongoDB with Replication on a set of Compute Engine instances


Deploy Bitnami MEAN on a Compute Engine instance:

From the Cloud Marketplace, select the MongoDB with Replication template.
Review the information and cost. Click Launch on Compute Engine to proceed.
Review the default zone, number of nodes and arbiters, machine type, boot disk size and other
parameters and modify as needed. Ensure that the Allow HTTP traffic and Allow HTTPS traffic boxes
are checked in the firewall configuration and that the default zone matches the zone for the Bitnami
MEAN instance. Click Deploy to proceed with the deployment.
The Cloud Marketplace deploys Bitnami MEAN on multiple Compute Engine instances. You can
monitor the progress of the deployment from the Deployment Manager. Once deployed, note the
password for the MongoDB database. Then, click the Manage link for each instance in the
Deployment Manager and note its internal IP address from the corresponding instance detail page.
Page 7
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur

Connect the MEAN application to the Bitnami MongoDB with Replication cluster
Before proceeding, confirm that the Bitnami MEAN instance and the Bitnami MongoDB with
Replication cluster instances are on the same VPC network. You can check this by visiting each
instance's detail page from the Deployment Manager and viewing the network name in the Network
interfaces section. If the Bitnami MEAN instance and the Bitnami MongoDB with Replication cluster
instances are not on the same network, configure VPC peering between the two networks before
proceeding.

Reconfigure the MEAN application to use the Bitnami MongoDB with Replication cluster:

From the Bitnami MEAN instance, login to the Bitnami MongoDB with Replication cluster using the
mongo command-line client. Use the internal IP address of the primary MongoDB node as the host IP
address and enter the password obtained from the Deployment Manager when prompted.

mongo --host XX.XX.XX.XX admin --username root -p

Once logged in, create a new database and user account for the application:

use mydb
db.createUser(
{
user: "myuser",
pwd: "mypass",
roles: [ "readWrite" ]
}
)
exit

Modify the application configuration to use the new Bitnami MongoDB with Replication cluster and
credentials by modifying the /opt/bitnami/apps/myapp/htdocs/config.json file as shown below.
Replace the XX, YY and ZZ placeholders with the internal IP addresses of all the nodes in the
Bitnami MongoDB with Replication cluster, starting with the primary node.

{
"connectionString":
"mongodb://myuser:mypass@XX.XX.XX.XX:27017,YY.YY.YY.YY:27017,ZZ.ZZ.ZZ.ZZ:27017/mydb?r
eplicaSet=rs0",
...
}

Restart the Express server:

cd /opt/bitnami/apps/myapp/htdocs
forever restart server.js

Browse to the public IP address of your Bitnami MEAN instance and confirm that it is working as
expected. Note that since the MEAN application is now connected to a different MongoDB database,
it is necessary to re-register a user account before logging in to the example application.

Test service continuity (optional)


In the Bitnami MongoDB with Replication template, one node in the cluster is designated as the
primary node and receives all write operations, while other nodes are designated as secondary nodes
which hold their own copies of the data set. If the primary node fails, the secondary nodes and

Page 8
I M.Tech II Sem CSE MST Unit-5 (R20) Prepared by:Dr Md.Umar Khan, KHIT, Guntur
arbiters elect a new primary automatically to ensure that writes continue without interruption. This
provides redundancy and ensures minimal downtime for your application.

Test service continuity for the MEAN application:

From the Deployment Manager, select the Bitnami MongoDB with Replication deployment.
From the list of instances in the deployment, select the primary instance and click the Manage button
to be redirected to the instance detail page.
Click the Stop button to stop the instance. Wait a few minutes for the instance to stop.
When the primary node stops, a new primary node is automatically elected from amongst the
secondary nodes to ensure continuity of service. To verify this, browse to the public IP address of
your Bitnami MEAN instance and confirm that you are still able to log in using the previously-
registered user account as well as register a new user account.

If you are able to perform the above tasks, your MEAN application is now operational and configured
to use the MongoDB replica set.

Cleaning up
After you have finished this tutorial, you can remove the resources you created on Google Cloud
Platform so you aren't billed for them any longer. You can delete the resources individually, or delete
the entire project.

Deleting the project


Visit the Resource Manager. Select the project you used for this tutorial and click Delete. Once
deleted, you cannot reuse the project ID.

Deleting individual resources


Navigate to the Deployment Manager. Select the deployments you used for this tutorial and click
Delete.

Next steps
Learn more about the topics discussed in this tutorial:

Bitnami MEAN documentation


Bitnami MongoDB with Replication documentation
MongoDB replication documentation

Page 9

You might also like