0% found this document useful (0 votes)
7 views14 pages

Mongo DB

MongoDB is a document-based NoSQL database that supports flexible schemas, horizontal scaling, and features like sharding and replication. It differs from traditional RDBMS by using collections and documents instead of tables and rows, and it allows for dynamic data models. Key features include support for ad hoc queries, indexing, and a variety of data types, making it suitable for high availability and performance in modern applications.

Uploaded by

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

Mongo DB

MongoDB is a document-based NoSQL database that supports flexible schemas, horizontal scaling, and features like sharding and replication. It differs from traditional RDBMS by using collections and documents instead of tables and rows, and it allows for dynamic data models. Key features include support for ad hoc queries, indexing, and a variety of data types, making it suitable for high availability and performance in modern applications.

Uploaded by

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

MongoDB

MongoDB is a document-based NoSQL database.


It is an open-source document-oriented database.
It requires no fixed schema definition.
Mongo DB stores data as Binary JSON or BSON.
It supports horizontal scaling. - the correct choice when it comes to handling big
data by the virtue of their design.
Several servers instance group together as a cluster to support Mongo DB as a
distributed system.
MongoDB uses MongoDB query language and supports Adhoc queries, Replication, and
Sharding.
A simple MongoDB document Structure:
{
title: 'Geeksforgeeks',
by: 'Harshit Gupta',
url: 'https://www.geeksforgeeks.org',
type: 'NoSQL'
}

Sharding is a feature of MongoDB that helps it to operate as a distributed data system

MongoDB vs RDBMS:
We can directly compare the MongoDB NoSQL with the RDBMS and map the varied
terminologies in the two systems: The RDBMS table is a MongoDB collection, the column is
a field, the tuple/row is a document, and the table join is an embedded document. The typical
schema of a relational database shows the number of tables and the relationship between the
tables, but MongoDB does not follow the concept of relationship.
MongoDB differs from RDBMS. This blog has elucidated nine different comparisons
between the two.

MongoDB RDBMS
Document-oriented and non-relational
Relational database
database

Document-based Row-based

Field-based Column based


Collection based and key-value pair Table based

Gives JavaScript client for querying Doesn’t give JavaScript for querying

Relatively easy to setup Comparatively not that easy to setup

Unaffected by SQL injection Quite vulnerable to SQL injection

Has dynamic schema and ideal for Has predefined schema and not good for
hierarchical data storage hierarchical data storage

100 times faster and horizontally scalable


By increasing RAM, vertical scaling can happen
through sharding

MongoDB vs MySQL
The following table explains the differences between MongoDB and MySQL

MongoDB MySQL
The query language is javascript The query language is a structured query language

It represents data as JSON documents It represents data in tables and rows.

Defining the schema is not required Defining tables and columns is required

It does not support JOIN It supports JOIN

MongoDB was built with high Although the MySQL idea does not allow for
availability and scalability in mind and effective replication and sharding, it does let users
offers replication and sharding out of the retrieve related data via joins, which reduces
box. duplication.

Because of its design, MongoDB is less


It has a risk of SQL injection attacks.
of an attack.

MongoDB Architecture
MongoDB employs the single-master architecture meaning there is a
primary machine taking charge of all client-side write operations. All other
instances you add later to the cluster constitute the secondary nodes, which
commonly handle all the read operations.
MongoDB achieves replication using the concept replica sets. A replica
set is a group of mongod instances that host the same data set. One of the nodes
is selected as the primary or main node. This is called the primary node. All
others are called secondary nodes. The primary node receives all the operations
from the user and the secondaries are updated from the primary one by using the
same operation to maintain consistency.
If the primary node goes down, one of the secondary nodes is selected as the
primary node and the operations are carried forward. When the fallen node
recovers, it joins the cluster as the secondary nodes. We can control our cluster
of mongo instances using Mongo Atlas.

Mongo clusters are created based on the idea of horizontal scaling and adding of instances.

Sharding in Mongo DB
Sharding is used by MongoDB to store data across multiple machines. It uses
horizontal scaling to add more machines to distribute data and operation with respect to the
growth of load and demand.
Sharding arrangement in MongoDB has mainly three components:
Shards or replica sets: Each shard serves as a separate replica set. They store all the data.
They target to increase the consistency and availability of the data.
Configuration Servers: They are like the managers of the clusters. These servers contain the
cluster's metadata. They actually have the mapping of the cluster's data to the shards. When a
query comes, query routers use these mappings from the config servers to target the required
shard.
Query Router: The query router is mongo instances which serve as interfaces for user
applications. They take in the user queries from the applications and serve the applications
with the required results. Usually, there are multiple query router per cluster for load
distribution.

MongoDB Data Types


MongoDB supports a wide range of datatypes, such as:
String − Must be UTF-8 valid
Integer − Stores a numerical value of 32 bit or 64 bit depending upon the server
Boolean − Stores true/ false value
Double − Stores floating point values
Min/Max keys − Compares a value against the lowest and highest BSON elements
Arrays − Stores arrays, lists, or multiple values into one key
Date − Stores the current date or time in UNIX format
Timestamp − Useful for keeping a record of the modifications or additions to a document
Object − Used for embedded documents
Object ID − Stores the ID of a document
Binary data − For storing binary data
Null − Stores a null value
Symbol − Used identically to a string but mainly for languages that have specific symbol
types
Code − For storing JavaScript code into the document
Regular expression − Stores regular expression

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.

12. It also supports:

o JSON data model with dynamic schemas


o Auto-sharding for horizontal scalability
o Built in replication for high availability
o Now a day many companies using MongoDB to create new types of applications,
improve performance and availability.

Distributed Data Platform


The technology gives you enough flexibility across various data centers with good
consistency.

Fast and Iterative Development


A flexible data model with dynamic schema, and powerful GUI and command-line tools,
makes it fast for developers to build and evolve applications.

Flexible Data Model


MongoDB stores data in flexible JSON-like documents, which makes data persistence and
combining easy.

Reduced TCO (Total Cost of Ownership)


The operations team also can perform their job well, thanks to the Atlas Cloud service.
Costs are significantly lowered as MongoDB runs on commodity hardware.

Data Model Design


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 modelling is balancing the need of the application, the
performance characteristics of the database engine, and the data retrieval patterns.

MongoDB provides two types of data models: — Embedded data model and Normalized
data model. Based on the requirement, you can use either of the models while preparing doc.
Effective data models support our application needs in Mongo DB. The key consideration
for the structure of our documents is the decision to embed or to use references.

Compatibility
We can use the following data models for deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Atlas is a multi-cloud database service by the same people that build
MongoDB. Atlas simplifies deploying and managing your databases while offering the
versatility you need to build resilient and performant global applications on the cloud
providers of your choice.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Enterprise is available for MongoDB Enterprise subscribers and includes several
additional features including LDAP authentication, Kerberos authentication, and System
Event Auditing.
MongoDB Community: The source-available, free-to-use, and self-managed version of
MongoDB

Embedded Data Models


With MongoDB, you may embed related data in a single structure or document. These
schemata are generally known as "denormalized" models, and take advantage of MongoDB's
rich documents.
Consider the following diagram: we are getting the details of employees in three different
documents namely, Personal_details, Contact and, Address, you can embed all the three
documents in a single one as shown below

{
_id: ,
Emp_ID: "10025AE336"
Personal_details:{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
},
Contact: {
e-mail: "radhika_sharma.123@gmail.com",
phone: "9848022338"
},
Address: {
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
}

Embedded data models allow applications to store related pieces of information in the same
database record. As a result, applications may need to issue fewer queries and updates to
complete common operations.
In general, use embedded data models when:
We have "contains" relationships between entities. Model One-to-One Relationships with
Embedded Documents.
we have one-to-many relationships between entities. In these relationships the "many" or
child documents always appear with or are viewed in the context of the "one" or parent
documents. See Model One-to-Many Relationships with Embedded Documents.
In general, embedding provides better performance for read operations, as well as the ability
to request and retrieve related data in a single database operation. Embedded data models
make it possible to update related data in a single atomic write operation.
To access data within embedded documents, use dot notation to "reach into" the embedded
documents. See query for data in arrays and query data in embedded documents for more
examples on accessing data in arrays and embedded documents.
Embedded Data Model and Document Size Limit
Documents in MongoDB must be smaller than the maximum BSON document size.
For bulk binary data, consider GridFS.

Normalized Data Models


Normalized data models describe relationships using references between documents.
In general, use normalized data models:
 When embedding would result in duplication of data but would not provide sufficient
read performance advantages to outweigh the implications of the duplication.
 To represent more complex many-to-many relationships.
 To model large hierarchical data sets.
MongoDB also provides referencing to join data across collections.
For example, you can re-write the above document in the normalized model as:
\Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"
}
Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
}
Contact:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
e-mail: "radhika_sharma.123@gmail.com",
phone: "9848022338"
}
Address:
{
_id: <ObjectId104>,
empDocID: " ObjectId101",
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"

In detail let us know the difference between RDBMS and MongoDB


schema design
Suppose a client needs a database design for his blog/website and see the differences between
RDBMS and MongoDB schema design. Website has the following requirements.
Every post has the unique title, description and url.
Every post can have one or more tags.
Every post has the name of its publisher and total number of likes.
Every post has comments given by users along with their name, message, data-time and likes.
On each post, there can be zero or more comments.
In RDBMS schema, design for above requirements will have minimum three tables.

While in MongoDB schema, design will have one collection post and the following structure

{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
},
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
}
]
}
So while showing the data, in RDBMS you need to join three tables and in MongoDB, data
will be shown from one collection only.
Kickstart Your

MongoDB CRUD Operations

CRUD operations create, read, update, and delete documents.


You can connect with driver methods and perform CRUD operations for deployments hosted
in the following environments:

 MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

 MongoDB Enterprise: The subscription-based, self-managed version of MongoDB

 MongoDB Community: The source-available, free-to-use, and self-managed version


of MongoDB

To learn more about performing CRUD operations in the UI for deployments hosted in
MongoDB Atlas, see Create, View, Update, and Delete Documents.

Create Operations

Create or insert operations add new documents to a collection. If the collection does not
currently exist, insert operations will create the collection.

MongoDB provides the following methods to insert documents into a collection:

 db.collection.insertOne() New in version 3.2

 db.collection.insertMany() New in version 3.2

In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

For examples, see Insert Documents.

Read Operations

Read operations retrieve documents from a collection; i.e. query a collection for documents.
MongoDB provides the following methods to read documents from a collection:

 db.collection.find()
You can specify query filters or criteria that identify the documents to return.

click to enlarge

For examples, see:

 Query Documents

 Query on Embedded/Nested Documents

 Query an Array

 Query an Array of Embedded Documents

Update Operations

Update operations modify existing documents in a collection. MongoDB provides the


following methods to update documents of a collection:

 db.collection.updateOne() New in version 3.2

 db.collection.updateMany() New in version 3.2

 db.collection.replaceOne() New in version 3.2

In MongoDB, update operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to update. These filters use the
same syntax as read operations.

For examples, see Update Documents.

Delete Operations
Delete operations remove documents from a collection. MongoDB provides the following
methods to delete documents of a collection:

 db.collection.deleteOne() New in version 3.2

 db.collection.deleteMany() New in version 3.2

In MongoDB, delete operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to remove. These filters use
the same syntax as read operations.

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