0% found this document useful (0 votes)
15 views

UNIT V iot r20

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

UNIT V iot r20

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT V: Mongo DB: Introduction, Architecture, Features, Examples, Database Creation &

Collection in Mongo DB. Deploying Applications: Web hosting & Domains, Deployment Using
Cloud Platforms.

Mongo DB: Introduction

MongoDB t provides basic and advanced concepts of SQL. Our MongoDB tutorial is designed
for beginners and professionals.

MongoDB is a No SQL database. It is an open-source, cross-platform, document-oriented


database written in C++.

Our MongoDB tutorial includes all topics of MongoDB database such as insert documents,
update documents, delete documents, query documents, projection, sort() and limit() methods,
create a collection, drop collection, etc. There are also given MongoDB interview questions to
help you better understand the MongoDB database.

What is MongoDB

MongoDB is an open-source document database that provides high performance, high


availability, and automatic scaling.

In simple words, you can say that - Mongo DB is a document-oriented database. It is an open
source product, developed and supported by a company named 10gen.

MongoDB is available under General Public license for free, and it is also available under
Commercial license from the manufacturer.

The manufacturing company 10gen has defined MongoDB as:

"MongoDB is a scalable, open source, high performance, document-oriented database." - 10gen

MongoDB was designed to work with commodity servers. Now it is used by the company of all
sizes, across all industry.

History of MongoDB

The initial development of MongoDB began in 2007 when the company was building a platform
as a service similar to window azure.

MongoDB was developed by a NewYork based organization named 10gen which is now known
as MongoDB Inc. It was initially developed as a PAAS (Platform as a Service). Later in 2009, it
is introduced in the market as an open source database server that was maintained and supported
by MongoDB Inc.
The first ready production of MongoDB has been considered from version 1.4 which was
released in March 2010.

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

Purpose of Building MongoDB

It may be a very genuine question that - "what was the need of MongoDB although there were
many databases in action?"

There is a simple answer:

All the modern applications require big data, fast features development, flexible deployment, and
the older database systems not competent enough, so the MongoDB was needed.

The primary purpose of building MongoDB is:

o Scalability
o Performance
o High Availability
o Scaling from single server deployments to large, complex multi-site architectures.
o Key points of MongoDB
o Develop Faster
o Deploy Easier
o Scale Bigger

Example of Document-Oriented Database

MongoDB is a document-oriented database. It is a key feature of MongoDB. It offers a


document-oriented storage. It is very simple you can program it easily.

MongoDB stores data as documents, so it is known as document-oriented database.

FirstName = "John",
Address = "Detroit",
Spouse = [{Name: "Angela"}].
FirstName ="John",
Address = "Wick

Features of MongoDB
These are some important features of MongoDB:

1. Support ad hoc queries

In MongoDB, you can search by field, range query and it also supports regular expression
searches.

2. Indexing

You can index any field in a document.

3. Replication

MongoDB supports Master Slave replication.

A master can perform Reads and Writes and a Slave copies data from the master and can only be
used for reads or back up (not writes)

4. Duplication of data

MongoDB can run over multiple servers. The data is duplicated to keep the system up and also
keep its running condition in case of hardware failure.

5. Load balancing

It has an automatic load balancing configuration because of data placed in shards.

6. Supports map reduce and aggregation tools.

7. Uses JavaScript instead of Procedures.

8. It is a schema-less database written in C++.

9. Provides high performance.

10. Stores files of any size easily without complicating your stack.

11. Easy to administer in the case of failures.

Architecture
Important characteristics of MongoDB

1. Document-Oriented: MongoDB uses a document data model, which means that data is

stored in flexible, JSON-like documents instead of in a rigid, table-based structure. This

allows for greater flexibility and ease of use, as the structure of the data can change over time

without affecting the overall system.

2. High Scalability: MongoDB uses sharding to horizontally partition data across multiple

servers, making it easy to scale out as the amount of data grows.

3. High Availability: MongoDB provides built-in replication and automatic failover

capabilities, ensuring that data remains available even in the event of a node failure.

4. Optimized for heavy reads: MongoDB uses a leader-follower protocol, making it possible

to use replicas for heavy reading.

5. Strong Consistency: MongoDB provides strong consistency through its replica sets,

ensuring that all members of a replica set have the same data.

6. Atomicity at the document level: MongoDB ensures atomicity in concurrent write

operations at the document level. This means that write operations on a single document are

guaranteed to be atomic and isolated from each other, even when performed concurrently.

7. Rich Query Language: MongoDB supports a rich and powerful query language that allows

you to retrieve and manipulate data with ease.

8. Flexible Data Modeling: MongoDB allows for flexible and dynamic data modeling,

allowing for changes to the schema without affecting the overall system.

9. Indexing: MongoDB supports a wide range of indexing options, including secondary

indexes, text search, and geospatial indexing, making it easy to retrieve data quickly.
10. Built-in Aggregation Framework: MongoDB provides a built-in aggregation framework

for data analysis and reporting.

11. Community-Driven: MongoDB has a large and active community of users, developers, and

contributors, making it a well-supported and widely used database technology.

The MongoDB architecture consists of the following components:

1. Collection: A collection is a group of MongoDB Documents, which is equivalent to an

RDBMS table.
2. Document: A document is a set of key-value pairs, where a value can be any of the BSON

data types, including arrays and other documents.

3. Database: A database is a container for collections, which holds all the data for a particular

application.

4. Shard: A shard is a horizontal partition of data that is spread across multiple servers.

MongoDB uses sharding to distribute data across multiple nodes and support horizontal

scalability.

5. Replica Set: A replica set is a group of servers that maintain identical copies of the same

data. Replication provides high availability, durability, and data redundancy.

6. Query Router: Query Routers are the components of a MongoDB cluster that receive client

requests, determine the location of the required data, and direct the request to the appropriate

shard.

7. Configuration Servers: Configuration servers store metadata and configuration settings for

a MongoDB cluster. They are responsible for maintaining the mapping of shards to replica

sets.

In summary, MongoDB is widely used in modern web and mobile applications that need to

handle large amounts of rapidly changing data in real time.

Features

1. Ad-hoc queries for optimized, real-time analytics

When designing the schema of a database, it is impossible to know in advance all the queries that
will be performed by end users. An ad hoc query is a short-lived command whose value depends
on a variable. Each time an ad hoc query is executed, the result may be different, depending on
the variables in question.

Optimizing the way in which ad-hoc queries are handled can make a significant difference at
scale, when thousands to millions of variables may need to be considered. This is why
MongoDB, a document-oriented, flexible schema database, stands apart as the cloud database
platform of choice for enterprise applications that require real-time analytics. With ad-hoc query
support that allows developers to update ad-hoc queries in real time, the improvement in
performance can be game-changing.

MongoDB supports field queries, range queries, and regular expression searches. Queries can
return specific fields and also account for user-defined functions. This is made possible because
MongoDB indexes BSON documents and uses the MongoDB Query Language (MQL).

2. Indexing appropriately for better query executions

In our experience, the number one issue that many technical support teams fail to address with
their users is indexing. Done right, indexes are intended to improve search speed and
performance. A failure to properly define appropriate indices can and usually will lead to a
myriad of accessibility issues, such as problems with query execution and load balancing.

Without the right indices, a database is forced to scan documents one by one to identify the ones
that match the query statement. But if an appropriate index exists for each query, user requests
can be optimally executed by the server. MongoDB offers a broad range of indices and features
with language-specific sort orders that support complex access patterns to datasets.

Notably, MongoDB indices can be created on demand to accommodate real-time, ever-changing


query patterns and application requirements. They can also be declared on any field within any
of your documents, including those nested within arrays.

Learn more about MongoDB indexing

Best Practices for MongoDB Indexing


3. Replication for better data availability and stability

When your data only resides in a single database, it is exposed to multiple potential points of
failure, such as a server crash, service interruptions, or even good old hardware failure. Any of
these events would make accessing your data nearly impossible.

Replication allows you to sidestep these vulnerabilities by deploying multiple servers for disaster
recovery and backup. Horizontal scaling across multiple servers that house the same data (or
shards of that same data) means greatly increased data availability and stability. Naturally,
replication also helps with load balancing. When multiple users access the same data, the load
can be distributed evenly across servers.

In MongoDB, replica sets are employed for this purpose. A primary server or node accepts all
write operations and applies those same operations across secondary servers, replicating the data.
If the primary server should ever experience a critical failure, any one of the secondary servers
can be elected to become the new primary node. And if the former primary node comes back
online, it does so as a secondary server for the new primary node.

Learn more about MongoDB replication

4. Sharding

When dealing with particularly large datasets, sharding—the process of splitting larger datasets
across multiple distributed collections, or “shards”—helps the database distribute and better
execute what might otherwise be problematic and cumbersome queries. Without sharding,
scaling a growing web application with millions of daily users is nearly impossible.

Like replication via replication sets, sharding in MongoDB allows for much greater horizontal
scalability. Horizontal scaling means that each shard in every cluster houses a portion of the
dataset in question, essentially functioning as a separate database. The collection of distributed
server shards forms a single, comprehensive database much better suited to handling the needs of
a popular, growing application with zero downtime.

All operations in a sharding environment are handled through a lightweight process called
mongos. Mongos can direct queries to the correct shard based on the shard key. Naturally, proper
sharding also contributes significantly to better load balancing.

Learn more about MongoDB sharding

Best Practices for MongoDB Sharding

5. Load balancing

At the end of the day, optimal load balancing remains one of the holy grails of large-scale
database management for growing enterprise applications. Properly distributing millions of client
requests to hundreds or thousands of servers can lead to a noticeable (and much appreciated)
difference in performance.

Fortunately, via horizontal scaling features like replication and sharding, MongoDB supports
large-scale load balancing. The platform can handle multiple concurrent read and write requests
for the same data with best-in-class concurrency control and locking protocols that ensure data
consistency. There’s no need to add an external load balancer—MongoDB ensures that each and
every user has a consistent view and quality experience with the data they need to access

Examples

Structuring Document Data

MongoDB documents are formatted in BSON (an extended Binary form of JSON) , which
allows you ultimate flexibility in structuring data of all types. Below are just a few of the ways
you can structure your documents.
Storing Nested Data Structures

Perhaps the most powerful feature of document databases is the ability to nest objects inside of
documents. A good rule of thumb for structuring data in MongoDB is to prefer embedding data
inside documents to breaking it apart into separate collections, unless you have a good reason
(like needing to store unbounded lists of items, or needing to look up objects directly without
retrieving a parent document).

{_id: ObjectId("5effaa5662679b5af2c58829"),
email: “email@example.com”,
name: {given: “Jesse”, family: “Xiao”},
age: 31,
addresses: [{label: “home”,
street: “101 Elm Street”,
city: “Springfield”,
state: “CA”,
zip: “90000”,
country: “US”},
{label: “mom”,
street: “555 Main Street”,
city: “Jonestown”,
province: “Ontario”,
country: “CA”}]
}

Note that the name field is a nested object containing both given and family name components,
and that the addresses field stores an array containing multiple addresses. Each address can have
different fields in it, which makes it easy to store different types of data.
Using the MongoDB Shell

The MongoDB shell is a great tool for navigating, inspecting, and even manipulating document
data. If you’re running MongoDB on your local machine, firing up the shell is as simple as
typing mongo and hitting enter, which will connect to MongoDB at localhost on the standard
port (27017). If you’re connecting to a MongoDB Atlas cluster or other remote instance, then
add the connection string after the command mongo .

Here are a few quick shell examples:

List Databases

> show dbs;


admin 0.000GB
config 0.000GB
local 0.000GB
my_database 0.004GB
>

List Collections

> use my_database;


> show collections;
users
posts
>

Count Documents in a Collection

> use my_database;


> db.users.count()
20234
>
Find the First Document in a Collection

> db.users.findOne()
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com"
"age": 27
}
>

Find a Document by ID

> db.users.findOne({_id: ObjectId("5ce45d7606444f199acfba1e")})


{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com",
"age": 27
}
>

Querying MongoDB Collections

The MongoDB Query Language (MQL) uses the same syntax as documents, making it intuitive
and easy to use for even advanced querying. Let’s look at a few MongoDB query examples.

Find a Limited Number of Results

> db.users.find().limit(10)

>

Find Users by Family name

> db.users.find({"name.family": "Smith"}).count()


1
>

Note that we enclose “name.family” in quotes, because it has a dot in the middle.

Query Documents by Numeric Ranges

// All posts having “likes” field with numeric value greater than one:
> db.post.find({likes: {$gt: 1}})
// All posts having 0 likes
> db.post.find({likes: 0})
// All posts that do NOT have exactly 1 like
> db.post.find({likes: {$ne: 1}})

Sort Results by a Field

// order by age, in ascending order (smallest values first)


> db.user.find().sort({age: 1})
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com",
"age": 27
}
{
_id: ObjectId("5effaa5662679b5af2c58829"),
email: “email@example.com”,
name: {given: “Jesse”, family: “Xiao”},
age: 31
}
>

// order by age, in descending order (largest values first)


> db.user.find().sort({age: -1})
{
_id: ObjectId("5effaa5662679b5af2c58829"),
email: “email@example.com”,
name: {given: “Jesse”, family: “Xiao”},
age: 31
}
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com",
"age": 27
}
>

Managing Indexes

MongoDB allows you to create indexes, even on nested fields in subdocuments, to keep queries
performing well even as collections grow very large.

Create an Index

> db.user.createIndex({"name.family": 1})


Create a Unique Index
> db.user.createIndex({email: 1}, {unique: true})

Unique indexes allow you to ensure that there is at most one record in the collection with a given
value for that field – very useful with things like email addresses!

See Indexes on a Collection

> db.user.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "my_database.user"
},
{
"v" : 2,
"key" : {
"name.given" : 1
},
"name" : "name.given_1",
"ns" : "my_database.user"
}
]

Note that by default, collections always have an index on the _id field, for easy document
retrieval by primary key, so any additional indexes will be listed after that.

Drop an Index

> db.user.dropIndex("name.given_1")

Database Creation & Collection in Mongo DB


Database Creation & Collection in Mongo DB

In MongoDB, the first basic step is to have a database and collection in place. The database is
used to store all of the collections, and the collection in turn is used to store all of the documents.
The documents in turn will contain the relevant Field Name and Field values.

The snapshot below shows a basic example of how a document would look like.

The Field Names of the document are “Employeeid” and “EmployeeName” and the Field values
are “1” and “Smith’ respectively. A bunch of documents would then make up a collection in
MongoDB.

Creating a database using “use” command


Creating a database in MongoDB is as simple as issuing the “using” command. The following
example shows how this can be done.
Code Explanation:

 The “use” command is used to create a database in MongoDB. If the database does not
exist a new one will be created.

If the command is executed successfully, the following Output will be shown:

Output:

MongoDB will automatically switch to the database once created

Creating a Collection/Table using insert()


The easiest way to create a collection is to insert a record (which is nothing but a document
consisting of Field names and Values) into a collection. If the collection does not exist a new one
will be created.

The following example shows how this can be done.


db.Employee.insert
(
{
"Employeeid" : 1,
"EmployeeName" : "Martin"
}
)
Code Explanation:

 As seen above, by using the “insert” command the collection will be created.

Adding documents using insert() command


MongoDB provides the insert () command to insert documents into a collection. The following
example shows how this can be done.

Step 1) Write the “insert” command

Step 2) Within the “insert” command, add the required Field Name and Field Value for the
document which needs to be created.

Code Explanation:

1. The first part of the command is the “insert statement” which is the statement used to
insert a document into the collection.
2. The second part of the statement is to add the Field name and the Field value, in other
words, what is the document in the collection going to contain.
If the command is executed successfully, the following Output will be shown

Output:

The output shows that the operation performed was an insert operation and that one record was
inserted into the collection.

Deploying Applications: Web hosting & Domains

Web applications are software programs that run on web browsers and servers, and can provide
dynamic and interactive features for users. However, to make your web application accessible to
the public, you need to deploy it to a hosting service, which is a platform that provides the
necessary resources and infrastructure for your web application to run. In this article, you will
learn how to deploy web applications using hosting services, and what factors to consider when
choosing a hosting service

Types of hosting services


When selecting a hosting service for your web application, there are a few options to consider.
Shared hosting is the most affordable and straightforward option, however it also limits control,
security, and scalability. Dedicated hosting is the opposite of shared hosting, providing more
control and scalability but at a higher cost and requiring more technical skills to manage. VPS
hosting offers more flexibility, customization, and isolation than shared hosting but requires
more technical skills and resources. Lastly, cloud hosting is a modern and scalable option that
provides high availability, reliability, and performance but may have less control and security
than other options.

Factors to consider

Before you choose a hosting service for your web application, you should consider several
factors that may affect your web application's functionality and user experience. Cost is an
important factor to consider, as you should compare pricing plans and features of different
hosting services to find the one that suits your budget. You should also consider potential hidden
costs, such as bandwidth, storage, backups, updates, and support. Performance is another key
factor to consider, as you should evaluate the speed, uptime, and reliability of different hosting
services. Location of the servers should also be taken into account as it may affect the latency
and accessibility of your web application for your target audience. Security measures and
policies of different hosting services should be assessed in order to protect your web application
from cyberattacks, data breaches, and other threats. Encryption, authentication, backup, and
recovery options should also be considered for safeguarding your web application's data and
functionality. Lastly, you should anticipate the growth and change of your web application's
demand and features when choosing a hosting service that can accommodate them without
compromising performance or quality. Flexibility and ease of upgrading or downgrading your
hosting service is an important factor to consider in terms of cost and availability.
Deployment Using Cloud Platforms

Today, organizations have many exciting opportunities to reimagine, repurpose and reinvent
their businesses with the cloud. The last decade has seen even more businesses rely on it for
quicker time to market, better efficiency, and scalability. It helps them achieve lo ng-term digital
goals as part of their digital strategy.

Though the answer to which cloud model is an ideal fit for a business depends on your
organization's computing and business needs. Choosing the right one from the various types of
cloud service deployment models is essential. It would ensure your business is equipped with the
performance, scalability, privacy, security, compliance & cost-effectiveness it requires. It is
important to learn and explore what different deployment types can offer - around what
particular problems it can solve.

Read on as we cover the various cloud computing deployment and service models to help
discover the best choice for your business.

What Is A Cloud Deployment Model?

It works as your virtual computing environment with a choice of deployment model depending
on how much data you want to store and who has access to the Infrastructure.

Different Types Of Cloud Computing Deployment Models

Most cloud hubs have tens of thousands of servers and storage devices to enable fast loading. It
is often possible to choose a geographic area to put the data "closer" to users. Thus, deployment
models for cloud computing are categorized based on their location. To know which model
would best fit the requirements of your organization, let us first learn about the various types
Public Cloud

The name says it all. It is accessible to the public. Public deployment models in the cloud are
perfect for organizations with growing and fluctuating demands. It also makes a great choice for
companies with low-security concerns. Thus, you pay a cloud service provider for networking
services, compute virtualization & storage available on the public internet. It is also a great
delivery model for the teams with development and testing. Its configuration and deployment are
quick and easy, making it an ideal choice for test environments.

Private Cloud

Now that you understand what the public cloud could offer you, of course, you are keen to know
what a private cloud can do. Companies that look for cost efficiency and greater control over
data & resources will find the private cloud a more suitable choice.

It means that it will be integrated with your data center and managed by your IT team.
Alternatively, you can also choose to host it externally. The private cloud offers bigger
opportunities that help meet specific organizations' requirements when it comes to
customization. It's also a wise choice for mission-critical processes that may have frequently
changing requirements

Community Cloud

The community cloud operates in a way that is similar to the public cloud. There's just one
difference - it allows access to only a specific set of users who share common objectives and use
cases. This type of deployment model of cloud computing is managed and hosted internally or by
a third-party vendor. However, you can also choose a combination of all three.

Hybrid Cloud

As the name suggests, a hybrid cloud is a combination of two or more cloud architectures. While
each model in the hybrid cloud functions differently, it is all part of the same architecture.
Further, as part of this deployment of the cloud computing model, the internal or external
providers can offer resources.

Let's understand the hybrid model better. A company with critical data will prefer storing on a
private cloud, while less sensitive data can be stored on a public cloud. The hybrid cloud is also
frequently used for 'cloud bursting'. It means, supposes an organization runs an application on-
premises, but due to heavy load, it can burst into the public cloud.

Benefits of Hybrid Cloud

o Cost-Effectiveness - The overall cost of a hybrid solution decreases since it majorly uses
the public cloud to store data.
o Security - Since data is properly segmented, the chances of data theft from attackers are
significantly reduced.
o Flexibility - With higher levels of flexibility, businesses can create custom solutions that
fit their exact requirements

Limitations of Hybrid Cloud

o Complexity - It is complex setting up a hybrid cloud since it needs to integrate two or


more cloud architectures
o Specific Use Case - This model makes more sense for organizations that have multiple
use cases or need to separate critical and sensitive data

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy