0% found this document useful (0 votes)
4 views45 pages

Mongo DB

The document provides a comprehensive overview of MongoDB, a popular NoSQL database, including its data types, installation, configuration, and CRUD operations. It compares MongoDB with traditional RDBMS, highlighting its flexibility and schema-less nature. Additionally, it covers various data modeling techniques and common commands for database and collection management.
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)
4 views45 pages

Mongo DB

The document provides a comprehensive overview of MongoDB, a popular NoSQL database, including its data types, installation, configuration, and CRUD operations. It compares MongoDB with traditional RDBMS, highlighting its flexibility and schema-less nature. Additionally, it covers various data modeling techniques and common commands for database and collection management.
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

Mongo DB

• Introduction to MongoDB
• Overview of NoSQL Database
• Mongo DB, its data types
• How it compares to RDBMS
• How to install Mongo DB and configure its setup
• Creating database and tables
• Mongo DB data Modeling
• CRUD operations
Introduction to MongoDB
• MongoDB, the most popular NoSQL database, is an open-source document-
oriented database. The term ‘NoSQL’ means ‘non-relational’.
• It stores data in a type of JSON format called BSON.
• Records in a MongoDB database are called documents, and the field values may
include numbers, strings, Booleans, arrays, or even nested
documents.
{
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
tags: ["news", "events"],
date: Date()
}
Overview of NoSQL Database
• Non-Relational Database
• Does not require fixed Schema
• Avoid joins
• Easy to scale
• Greater Flexibility than SQL because it stores/handle structured,
semi-structured, Unstructured and polymorphic data in the form of
Graphs, Chats, objects etc.
Why we use NoSQL
• Hierarchical storage structure instead of a table-like structure.
• Constant addition of new features and functions
• Relationship between stored data is not important

Popular NoSQL Databases


• MongoDB(Document oriented)
• Redis(Key-Value)
• Cassandra(Wide-column)
• Neo4j(Graph oriented)
How it compares to RDBMS (SQL Vs NoSQL)
Types of databases — NoSQL
• Document-oriented databases
• key-value databases
• wide-column stores
• and graph databases
Document-oriented databases
• A document-oriented database stores data in documents similar to
JSON (JavaScript Object Notation) objects.
• Each document contains pairs of fields and values. The values can
typically be a variety of types, including things like strings, numbers,
Booleans, arrays, or even other objects.
• A document database offers a flexible data model, much suited for
semi-structured and typically unstructured data sets.
• They also support nested structures, making it easy to represent
complex relationships or hierarchical data.
• Examples of document databases are MongoDB and Couchbase.
Key-value databases

• A key-value store is a simpler type of database where each item


contains keys and values.
• Each key is unique and associated with a single value.
• They are used for caching and session management and provide high
performance in reads and writes because they tend to store things in
memory.
• Examples are Amazon DynamoDB and Redis.
Wide-column stores
• Wide-column stores store data in tables, rows, and dynamic columns.
• The data is stored in tables. However, unlike traditional SQL
databases, wide-column stores are flexible, where different rows can
have different sets of columns.
• These databases can employ column compression techniques to
reduce the storage space and enhance performance.
• The wide rows and columns enable efficient retrieval of sparse and
wide data.
• examples of wide-column stores are Apache Cassandra and HBase.
Graph databases
• A graph database stores data in the form of nodes and edges.
• Nodes typically store information about people, places, and things
(like nouns), while edges store information about the relationships
between the nodes.
• They work well for highly connected data, where the relationships or
patterns may not be very obvious initially.
• Examples of graph databases are Neo4J and Amazon Neptune.
How to install Mongo DB and configure its setup
1. Download MongoDB:
visit the MongoDB download page and select the appropriate version for Windows.
download mongo DB shell
Follow the installation instructions provided.
2. Install MongoDB:
Run the installer you downloaded.
Follow the setup wizard instructions.
Choose the Complete installation type, which installs MongoDB as a service.
3. Start MongoDB:
MongoDB should start automatically after installation. If not, you can
start it manually by running the mongo command in the Command
Prompt.
4. Connect to MongoDB:
Open a new Command Prompt window.
Run the mongo/mongosh command to connect to the MongoDB server.
Data Types
1. String
String is the most commonly used datatype. It is used to store data. A string must be UTF 8 valid in mongodb.
Example:
{
"intern_name": "Edward Bill",
"intern_skills": "Software Development",
"intern_salary": 7500,
"intern_status": true,
}

2. Integer
Integer is used to store the numeric value. It can be 32 bit or 64 bit depending on the server you are using.
Example:
{
"intern_name": "Edward Bill",
"intern_skills": "Software Development",
"intern_salary": 7500,
"intern_status": true,
}
Intern_salary is of the type integer since it stores a numeric number.
3. Double
Double datatype stores floating point values.
{
"intern_name": "Edward Bill",
"intern_skills": "Software Development",
"intern_score": 87.75,
"intern_status": true,
}

4. Boolean
This datatype is used to store boolean values. It just shows YES/NO values.
{
"intern_name": "Edward Bill",
"intern_skills": " Software Development",
"intern_score": 87.75,
"intern_status": true,
}
5. Array
The array is stored using the array data type. We can store several values in a single key of the document with an array
data type.
{
" intern_name": "Edward Bill",
" intern_skills": ["Software Development", "C++", "Java"],
" intern_score": 87.75,
" intern_status": true,
}
6. Object
An embedded document is a key-value pair that is put inside another document. Embedded documents are stored
using the object data type.
{
"product_code": "0000-XYZ",
"product_price": 39.99,
"product_dimensions": {
"product _height": 1000,
"product_width": 90,
"product_depth": 600,
},
"product_availability": true,
}
Because it has its own set of key-value pairs, the product dimensions field in the example above is an embedded
document. As a result, this field is an Object field.

7. Date
The current date or time is stored in the ‘Date’ data type. The returning date can be done in a variety of ways; either a
string or a date object. There are three strategies that can be used in this situation.
Date() returns the current date as a string in mongosh.
new Date() returns the current date as a Date object.
ISODate() returns a date object as well.
Example:
{
"employee_name": "John Doe",
"employee_dob": ISODate("2004-04-10T12:45:42.389Z"),
"employee_marks": 80.40
}

8. Timestamp
The term "Timestamp" refers to a set of characters used to describe the date and time of an occurrence. The
timestamp data type is commonly used to track the creation, editing, and updating of documents. Such characters are
stored in the timestamp data type. To construct a timestamp, use the new Timestamp().
9. Null
It is used to store null values.
{
"product_code": "0000-XYZ",
"product_price": 39.99,
"product_color": null,
"product_availability": true,
}
Mongo DB data Modeling
• MongoDB Data modeling is the process of arranging unstructured data
from a real-world event into a logical data model in a database.
• There is no need to build a schema before adding data to MongoDB
database because MongoDB is flexible. This means that MongoDB
supports a dynamic database schema.

Relational Database Behavior Document Database Behavior


You must determine a table's schema before you insert data. Your schema can change over time as the needs of your
application change.
You often need to join data from several different tables to The flexible data model lets you store data to match the way
return the data needed by your application. your application returns data, and avoid joins. Avoiding joins
across multiple collections improves performance and reduces
your deployment's workload.
Mongo DB data Modeling
Embedded Data Modeling
• Embedded documents capture relationships between data by storing
related data in a single document structure.
• MongoDB documents make it possible to embed document structures in
a field or array within a document.
• These denormalized data models allow applications to retrieve and
manipulate related data in a single database operation.
• For many use cases in MongoDB, the denormalized data model is
optimal.
Reference Data Modeling
• References store the relationships between data by including links or
references from one document to another.
• Applications can resolve these references to access the related data.
Broadly, these are normalized data models.
CRUD operations
Creating database and tables

1. Database Commands
• To see all databases
> show dbs
• Create a new or switch databases
use <database-name>;
>use dbName
• View current Database
>db
• Delete Database
[Link]();
2. Collection Commands
• To see all collections
>show collections
• To create new collections
> [Link]('<collection-name>’);
-Create a collection named 'comments’
>[Link]('comments’)

• To delete a collection
>db.<collection-name>.drop();
-Drop a collection named 'comments’
>[Link]()
Insert Operation
[Link]({
key1: value1,
key2: value2,
// Additional fields as needed
});

[Link]({
'name': 'Harry',
'lang': 'JavaScript',
'member_since': 5
})
To insert many documents in the collections
[Link]([{
'name': 'Harry',
'lang': 'JavaScript',
'member_since': 5
},
{'name': 'Rohan',
'lang': 'Python',
'member_since': 3
},
{'name': 'Lovish',
'lang': 'Java',
'member_since': 4
}])
Search Operations
• To read all documents in the collections
> db.<collectionName>.find();
• To find only the first document occurred in the list
> db.<collectionName>.findOne({"name":"vinod"});
• To search a specific Document in the collection
> db.<collectionName>.find({ key: value });
• Setting limit and skip in results of Find
> db.<collectionName>.find().limit(5); // Limits the no of row in the
output
> db.<collectionName>.find().skip(5); // skip the first n
documentfrom the query result
• Count the number of rows in the output
>[Link]().count()
Update Operations
To update a existing document
db.<collectionName>.updateOne(
{ key: value },
{ $set: { updatedKey: updatedValue } }
);

[Link]({name: 'Shubham'},
{$set: {'name': 'Harry',
'lang': 'JavaScript',
'member_since': 51
}}, {upsert: true})
Deletion Operations
• To delete a single document
>[Link]({ key: value });
• To delete multiple documents
>[Link]({ key: value });
Queries
• Write a query to display all the employess details who is working in
department number 20.
• Write a query to display all the details of the employees whose name
is smith.
• WAQTD all the details of the employee’s whose job is salesmam &
working in deptno:20.
• WAQTD all the employee details whose job is clerk & working in dept
no:10.
• WAQTD all the employee details who is getting commission 300.
• WAQTD all the employee details who is getting commission greater
then 500.
• WAQTD all the employee details who is not getting commission.
• WAQTD all the employee details who is working in det no:20 and
getting salary below 2000.
• WAQTD all the employee details who is getting some commission.
Comparison operators in Mongo DB
• All the operators are predefined with $
Operators Description

$eq Matches the values of the fields that are equal to a specified value.

$ne Matches all values of the field that are not equal to a specified value.

$gt Matches values of the fields that are greater than a specified value.

$gte Matches values of the fields that are greater than equal to the specified value.

$lt Matches values of the fields that are less than a specified value

$lte Matches values of the fields that are less than equal to the specified value

$in Matches any of the values specified in an array.

$nin Matches none of the values specified in an array.

You might also like