UNIT V iot r20
UNIT V iot r20
Collection in Mongo DB. Deploying Applications: Web hosting & Domains, Deployment Using
Cloud Platforms.
MongoDB t provides basic and advanced concepts of SQL. Our MongoDB tutorial is designed
for beginners and professionals.
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
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.
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.
It may be a very genuine question that - "what was the need of MongoDB although there were
many databases in action?"
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.
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
FirstName = "John",
Address = "Detroit",
Spouse = [{Name: "Angela"}].
FirstName ="John",
Address = "Wick
Features of MongoDB
These are some important features of MongoDB:
In MongoDB, you can search by field, range query and it also supports regular expression
searches.
2. Indexing
3. 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
10. Stores files of any size easily without complicating your stack.
Architecture
Important characteristics of MongoDB
1. Document-Oriented: MongoDB uses a document data model, which means that data is
allows for greater flexibility and ease of use, as the structure of the data can change over time
2. High Scalability: MongoDB uses sharding to horizontally partition data across multiple
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
5. Strong Consistency: MongoDB provides strong consistency through its replica sets,
ensuring that all members of a replica set have the same data.
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
8. Flexible Data Modeling: MongoDB allows for flexible and dynamic data modeling,
allowing for changes to the schema without affecting the overall system.
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
11. Community-Driven: MongoDB has a large and active community of users, developers, and
RDBMS table.
2. Document: A document is a set of key-value pairs, where a value can be any of the BSON
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
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
Features
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).
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.
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.
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.
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
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 .
List Databases
List Collections
> db.users.findOne()
{
"_id": ObjectId("5ce45d7606444f199acfba1e"),
"name": {given: "Alex", family: "Smith"},
"email": "email@example.com"
"age": 27
}
>
Find a Document by ID
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.
> db.users.find().limit(10)
…
>
Note that we enclose “name.family” in quotes, because it has a dot in the middle.
// 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}})
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
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!
> 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")
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.
The “use” command is used to create a database in MongoDB. If the database does not
exist a new one will be created.
Output:
As seen above, by using the “insert” command the collection will be created.
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.
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
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.
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.
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.
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