MongoDB Part1
Course Objectives: This Course will enable students to
1. |
Master the leading
document-oriented NoSQL database, MongoDB Architecture, CRUD, Schema |
2. |
Design, Data Modelling and
Indexing using real-life case studies |
3. |
Learn how to design Schema
using Advanced Queries Course Outcomes |
Course
Outcomes: At the end of the course the student will be
able to:
1. |
Install, configure and setup the drivers to
use MongoDB with your programming language of choice |
K6 |
2. |
Gain an in-depth understanding of main
features of MongoDB and their use cases |
K2 |
3. |
Retrieve data in the database using
advanced querying |
K2 |
4. |
choice to build new types of applications
for mobile, cloud, e-commerce and and social technologies Perform Experiments
related to the following concepts |
K3 |
1.
Introduction to MongoDB and its
Architecture
MongoDB is a
popular and widely used document-oriented NoSQL database. It was developed by
MongoDB Inc. and was first released in 2009. MongoDB provides a flexible and
scalable approach to storing and retrieving data, making it suitable for a wide
range of applications.
Here are some key concepts and features of MongoDB:
Document-Oriented:
MongoDB stores data in flexible, JSON-like documents called BSON (Binary JSON).
A document can have a varying structure, allowing for a more dynamic and
schema-less data model compared to traditional relational databases.
Collections
and Documents: In MongoDB, documents are organized into collections,
which are analogous to tables in a relational database. Collections can contain
multiple documents, each with its own set of fields and values.
Schema
Flexibility: MongoDB allows you to change the structure of documents
within a collection without affecting other documents. This flexibility is
beneficial in scenarios where data evolves over time or when dealing with
semi-structured or unstructured data.
Query
Language: MongoDB provides a rich query language that supports
various operations, such as filtering, sorting, aggregation, and joining. The
query language is expressive and allows for complex queries to retrieve and
manipulate data.
Scalability
and High Availability: MongoDB is designed to scale
horizontally by distributing data across multiple servers or clusters. It
offers built-in support for sharding, which allows for distributing data across
multiple machines, and replica sets, which provide high availability and data
redundancy.
Indexing:
MongoDB supports indexing on fields within a collection, enabling efficient
querying and retrieval of data. Indexes can be created on single fields or
combinations of fields, improving query performance.
Rich
Functionality: MongoDB offers a range of features, including support
for geospatial queries to work with location-based data, text search capabilities,
and the ability to execute server-side JavaScript through its query language.
Community and
Ecosystem: MongoDB has a large and active community, which
contributes to its ecosystem. It offers official drivers for various
programming languages and frameworks, making it easy to integrate MongoDB into
different application stacks.
MongoDB is
widely used in various domains, such as web applications, content management
systems, real-time analytics, Internet of Things (IoT), and more. Its flexibility,
scalability, and ease of use have made it a popular choice for developers and
organizations seeking a modern database solution.
Fig.1. MongoDB Basic Data
Storage
ARCHITECTURE:
The architecture of
MongoDB is designed to provide scalability, high availability, and flexibility
in handling data. Let's explore the key components and their interactions
within a MongoDB deployment:
MongoDB Server: At the
core of MongoDB is the server process, which manages data storage, retrieval,
and processing. The server interacts with clients, executes queries and
commands, and performs data manipulations. It manages memory, storage, and
concurrency control to ensure efficient operations.
Sharding: Sharding
is the process of distributing data across multiple machines or clusters called
shards. It allows MongoDB to horizontally scale by partitioning data and
workload across shards based on a chosen shard key. Each shard is an
independent replica set or cluster that stores a portion of the data.
Replica Sets: A replica
set is a group of MongoDB servers that maintain the same data set, providing
redundancy and high availability. Within a replica set, there is one primary
node that handles all write operations and multiple secondary nodes that
replicate data from the primary. If the primary node fails, one of the
secondaries automatically becomes the new primary.
Documents and
Collections: Data in MongoDB is organized into documents, which are
JSON-like data structures. Documents are grouped into collections, which are analogous
to tables in a relational database. Collections can have indexes defined on one
or more fields to optimize query performance.
Indexes: MongoDB
supports indexing on fields within collections. Indexes are used to improve
query performance by allowing faster data retrieval based on specific fields.
MongoDB offers various index types, including single-field indexes, compound
indexes, text indexes for full-text search, and geospatial indexes for working
with location-based data.
Query Router: In a sharded
cluster, the query router, also known as the mongos process, acts as the
interface between client applications and the underlying shards. The query
router receives queries from clients, determines which shards contain the
relevant data based on the shard key, and forwards the queries to the
appropriate shards.
Config Servers: The config
servers store metadata and configuration information about the sharded cluster,
such as the location of data ranges and shard mappings. The query router uses
this information to route queries efficiently to the appropriate shards. Config
servers are typically deployed as a replica set for redundancy and high
availability.
Client Applications
and Drivers: Client applications interact with MongoDB using drivers
or libraries specific to their programming language. MongoDB provides official
drivers for various languages, allowing developers to connect, query, and
manipulate data from their applications.
These components work
together to provide a distributed, scalable, and fault-tolerant database
system. MongoDB's architecture allows for horizontal scaling by adding more
shards, provides high availability through replica sets, and supports flexible
data modeling with its document-oriented approach.
2. Installations of MongoDB Server, Compass and
Shell
The
general steps for installing MongoDB Server, Compass and MongoShell:
1. MongoDB Server Installation:
Step1: Visit the MongoDB Download Center (https://www.mongodb.com/try/download/community) in your web browser.
Step 2: Select the
appropriate version of MongoDB Server for your operating system. Choose the
Community Server edition, which is free.
Step 3: Choose the version
and operating system that matches your requirements and click on the download
button.
Step 4: Once the download
is complete, open the installer file.
Step 5: Follow the
installation wizard and accept the license agreement.
Step 6: Choose the
components you want to install. Make sure to select the MongoDB Server option.
Step 7: Choose the
installation directory or keep the default location.
Step 8: Select the options
for MongoDB as per your preferences, such as enabling MongoDB as a service or
adding MongoDB to the system's PATH.
Step 9: Click on the
"Install" button to start the installation process.
Step 10: Once the
installation is complete, you can proceed to configure and start MongoDB
Server.
2. MongoDB Compass
Installation:
Step 1: Visit the MongoDB Download Center (https://www.mongodb.com/try/download/compass) in your web browser.
Step 2: Select the
appropriate version of MongoDB Compass for your operating system. Choose the
Community edition, which is free.
Step 3: Choose the version
and operating system that matches your requirements and click on the download
button.
Step 4: Once the download
is complete, open the installer file.
Step 5: Follow the
installation wizard and accept the license agreement.
Step 6: Choose the
components you want to install. Make sure to select MongoDB Compass.
Step 7: Choose the
installation directory or keep the default location.
Step 8: Select the options
for MongoDB Compass as per your preferences.
Step 9: Click on the
"Install" button to start the installation process.
Step 10: Once the
installation is complete, you can launch MongoDB Compass.
3. MongoShell:
To set up the MongoDB Shell, you can follow these steps:
Step 1: Visit the MongoDB
Download Center (https://www.mongodb.com/try/download/shell) in your web
browser.
Step 2: Select the appropriate version of MongoDB Shell for your
operating system. Choose the Community edition, which is free.
Step 3: Choose the version and operating system that matches your
requirements and click on the download button.
Step 4: Once the download is complete, extract the downloaded contents
Step5: Launch mongosh application, accept default connect string (press
enter) and run commands
3. CRUD Operations in MONGODBExercise–I: Student Database
AIM: To perform CRUD operations in Student Database
THEORY:
CRUD in MongoDB refers to the basic operations that can be performed on
data stored in a MongoDB database. CRUD stands for Create, Read, Update, and
Delete, representing the four fundamental actions that can be applied to
database records or documents.
Create (C): This operation is used to insert new documents into a MongoDB
collection. To create a new document, you typically construct a JSON-like
object with the desired data fields and values, and then insert it into the
collection using the insertOne() or insertMany() method.
Read
(R): The read operation is used to retrieve data from a
MongoDB collection. MongoDB provides several methods to query documents,
including find()
, findOne()
, and aggregate()
.
You can use query criteria to filter the results and specify the fields to be
returned.
Update (U): The update operation allows you to modify existing documents in a
collection. MongoDB provides methods like updateOne() and updateMany() to
update documents. You specify a filter to identify the documents to be updated
and the modifications to be applied. Here's an example:
Delete
(D): The delete operation is used to remove documents
from a collection. MongoDB provides methods such as deleteOne()
and deleteMany()
to delete documents that match a specified filter
PROGRAM:
Create database, Create collection, insert data, find, find one,
sort, limit, skip, distinct, projection.
Create a student database with the fields: (SRN, Sname, Degree,
Sem, CGPA)>
>use student1
Switched to db student1
>db.stud1col1.insert({srn:110,sname:"Rahul",degree:"BCA",sem:6,CGPA:7.9})
OR
> doc1=({srn:110,sname:"Rahul",degree:"BCA",sem:6,CGPA:7.9})
>db.studcol1.insert (doc1)
Note:insert 10 such documents.
Questions:1.display all the documents
>db.studcol1.find()
2.Display all the students in BCA
>db.studcol1.find({degree:"BCA"})
3.Display all the students in ascending order
>db. studcol1.find().sort({sname:1})
4.Display first 5 students
>db. studcol1.find().limit(5)
5.display students 5,6,7
>db. studcol1.find().skip(4).limit(3)
6.list the degree of student "Rahul"
>db. studcol1.find({sname : "Rahul"},{degree:1})
7.Display students details of 5,6,7 in descending order of
percentage
>db. studcol1.find().sort({CGPA:-1}).skip(4).limit(3)
8.Display the number of students in BCA
>db. studcol1.find({degree:"BCA"}).count()
4. CRUD Operations in MONGODBExercise–II: Employee Database
AIM:
To perform CRUD Operations in Employee database
PROGRAM:
Update modifiers ($set, $unset,
$inc, $push, $pushAll, $pull, $pullAll, $addToSet)
Create an employee database
with the fields: {eid, ename, dept, desig, salary, yoj, address{dno,street,
locality, city}}
> use empdb
switched to db empdb
> doc1 = {eid:001,
ename:"Rahul", dept:"production",
desig:"developer", salary:30000, yoj:2015,address:{dno:397, street:2,
locality:"rmnagar", city:"bangalore"} }
>db.emp.insert(doc1)
WriteResult({
"nInserted" : 1 })
Note:insert 10 documents.
Questions:1.Display all the employees
with salary in range (50000, 75000)
>db.emp09.find({salary:{$gt:50000,
$lt:75000}})
2.Display all the employees
with desig developer>db.emp09.find({desig:"developer"}
3.Display
the Salary of “Rahul”
>db.emp09.find({ename:"Rahul"},{salary:1})
4.Display the city of employee
>db.emp09.find({ename:"Rahul"},{"address.city":1})
5.Update the salary of developers by 5000
>db.emp09.update({desig:"developer"},{$inc:{"salary":5000}})
6.Add field age to employee Rahul
>db.emp09.update({ename:"Rahul"},{$set:{age:"22"}})
7.Remove YOJ from “Rahul”
Comments
Post a Comment