UNIT III MONGO DB 9
Understanding NoSQL and MongoDB – Building MongoDB Environment – User accounts – Access control – Administering
databases – Managing collections – Connecting to MongoDB from [Link] – simple applications
Database:
A database for web development refers to a structured system used to store, manage, and retrieve data that is essential for the functioning
of web applications.
In web development, databases act as the backbone for managing dynamic content such as user profiles, posts, transactions, and more.
Role of a Database in Web Development:
The database plays several important roles in web development:
• Data Storage: Web applications typically store data like user accounts, product information, blog posts, comments, and more.
• Data Retrieval: When a user interacts with the site (e.g., searches for a product or logs in), the web application retrieves the relevant data
from the database.
• Data Manipulation: The database supports CRUD operations (Create, Read, Update, Delete) to handle data inputs and updates.
• Dynamic Content Generation: Websites generate pages dynamically by querying databases for the latest data (e.g., new articles or user-
specific content like notifications).
Common Database Operations in Web Development
• User Authentication: Verifying credentials stored in the database (e.g., password hash comparison).
• Form Submission: Storing and processing data submitted via web forms (e.g., sign-up forms, surveys).
• Data Filtering and Sorting: Allowing users to search, sort, and filter data (e.g., search for products by price, category).
• Pagination: Breaking down large datasets into manageable chunks to improve performance and user experience.
Types of Databases
Relational Databases (SQL)
• Relational databases organize data into structured tables with rows and columns. Relationships between tables are established
using keys (primary and foreign keys). SQL (Structured Query Language) is used for interacting with the database.
Examples:
• MySQL: Widely used in web applications (e.g., WordPress).
• PostgreSQL: An advanced, open-source relational database with support for complex queries.
• SQLite: Lightweight and self-contained, often used for small or embedded applications.
Non-Relational Databases (NoSQL)
• NoSQL databases are more flexible and often used when data doesn’t fit well into structured tables.
• They handle unstructured or semi-structured data such as JSON documents, graphs, or key-value pairs.
For example, a YouTube video with user comments is unstructured:
• The video (multimedia)
• The comments (free text in different languages, emojis, slang )
• They are often chosen for their scalability and performance with large, distributed systems.
Examples:
• MongoDB: Document-oriented database that stores data in JSON-like format.
• Cassandra: Designed for handling large amounts of data across many servers.
• Firebase: Real-time NoSQL database popular for mobile and web apps.
Database Connectivity in Web Development:
Server-Side Code: Languages like PHP, Python (Django, Flask), JavaScript ([Link]), Ruby, and Java have libraries or frameworks that
support connecting to and interacting with databases. (ORMs and API Endpoints)
When choosing and designing a database for a web application, several factors come into play:
Scalability:
Web applications often need to handle a growing number of users, which places increasing demands on the database.
• Relational Databases scale vertically
• NoSQL Databases like MongoDB and Cassandra are more suited for horizontal scaling
Performance:
• Database performance can impact the speed of web pages and user interactions.
• Techniques like indexing, query optimization, and caching are used to improve performance.
Security (Authentication and Authorization, Encryption, Backup and Recovery), Consistency vs Availability.
Understanding NoSQL and MongoDB :
• NoSQL refers to "Not Only SQL," a broad category of database management systems that do not follow the traditional relational database
structure.
• NoSQL databases are designed to handle large amounts of unstructured, semi-structured, or structured data.
• They are more flexible, scalable, and suited for modern applications, especially those that require real-time data processing, distributed
systems, and horizontal scaling.
Types of NoSQL Database:
• Key-value Pair based
• Document-based databases
• Column-oriented databases
• Graph-based databases
Key-value Pair based:
• Key-value pair is the most simple type of NoSQL database. It only has 2 columns, named ‘key’ and ‘value’, where the key can only have string values while
the value can store JSON, strings, Blob, XML, etc.
• Key: A unique identifier (usually a string) that allows you to retrieve, update, or delete the corresponding value.
• Value: The actual data associated with the key. This can be anything from a simple string or number to a more complex data structure like JSON, an image, or a
serialized object.
{
"name": "Alice",
"email": "alice@[Link]",
"age": 30
}
• Session Management, Caching Solutions, User Preferences and Profiles (Mobile), Systems monitoring and logging applications.
Advantages: Dis-Advantages:
• Extremely Fast Owing to it’s simplicity • Not the perfect solution if you frequently update the data values & Complex Data
• Best fit for cases where data is not highly related • No Relationships Between Data and No Structure for Values
• Session-based applications like shopping carts
Document-based databases:
• The document-based database is a nonrelational database. Instead of storing the data in rows and columns (tables), it uses the documents to store the data in
the database.
• Documents store data in field-value pairs. The values can be a variety of types and structures, including strings, numbers, dates, arrays, or objects. Documents
can be stored in formats like JSON, BSON, and XML.
• Mobile Applications (Instagram and Snapchat), Gaming Applications (Online multiplayer games), CMS (WordPress and Drupal)
Bank Database contains two tables whose attributes are listed as follows :
SQL: JSON Document:
Advantages: Dis-Advantages:
• Schema Flexibility • Limited Querying Capabilities
• Nested Data Storage like arrays and nested objects • Data Redundancy (Increase storage costs and lead to inconsistencies)
within single documents
Column-oriented databases:
• Stores data in columns rather than rows. This architecture is particularly beneficial for certain types of analytical workloads, such as those found in data
warehousing and big data applications
• The most significant benefit of having column-oriented databases is that you can store large amounts of data within a single
column.
• Business Intelligence and Analytics ( Power BI), Customer Analytics (E-Commerce), Healthcare Analytics, Internet of Things (IoT)
Analytics
UserID(Smart Cities)
Name Age UserID: [1, 2, 3]
--------------------------------
SQL Name: ["Alice", "Bob", "Charlie"]
Column Oriented
1 Alice 30 Age: [30, 25, 35]
2 Bob 25
3 Charlie 35
Advantages: Dis-Advantages:
• High Query Performance • Not optimized for transaction-heavy workloads (OLTP)
• Designed to handle large-scale data • Managing complex relationships (like foreign keys) can be more challenging in columnar
databases compared to row-oriented databases
• Suitable for Big Data and Analytics
Graph-based databases :
• Graph-based databases are a type of NoSQL database designed to represent and store data in the form of graphs, consisting of nodes (entities) and edges
(relationships).
• This structure allows for efficient representation of complex relationships and enables powerful querying capabilities, especially for connected data.
• Social Networks (Facebook), Recommendation Systems (Netflix), Fraud Detection (Payment System), Chain Management (Logistics), CRM (Sales & Marketing)
Graph Structure: Data is organized as a graph, where:
• Nodes represent entities (e.g., users, products, locations).
• Edges represent relationships between nodes (e.g., friendships, transactions, connections).
• Properties can be associated with both nodes and edges to provide additional information.
Advantages: Dis-Advantages:
• Designed to handle complex queries involving • Complexity in Learning
relationships and traversals
• Natural Representation of Relationships
Key Differences:
Feature NoSQL MongoDB
Type General category of databases Specific NoSQL database
Various models (key-value, document, column-family,
Data Model Document-oriented model
graph)
Depends on the type (JSON, key-value pairs, wide
Storage Format BSON (Binary JSON)
columns)
Dynamic schema (documents can have different
Schema Flexible schema or schema-less
structures)
Query Language Varies by database type MongoDB query language (similar to JSON)
Scalability Generally designed for horizontal scaling Built-in support for sharding and replication
Not necessarily ACID compliant (eventual consistency
ACID Compliance Offers ACID transactions since version 4.0
is common)
Various use cases depending on the type (e.g., Often used for content management, e-commerce, and
Use Cases
caching, analytics, real-time processing) real-time analytics
Examples Cassandra, Redis, Couchbase, Neo4j MongoDB
Building MongoDB Environment:
Mongo DB:
Mongo DB:
Mongo DB:
Mongo DB:
Mongo DB:
• A collection is similar to a table in relational databases like MySQL, but it doesn't enforce a fixed schema, meaning each document (record) in a collection can
have different fields and data types.
Mongo DB:
Mongo DB:
Mongo DB:
Mongo DB:
Mongo DB:
Mongo DB (Command Mode):
• Find Mongo Shell – Bin Folder
Mongo DB (Command Mode):
• Find Mongo Shell – Bin Folder
Mongo DB (Command Mode):
Mongo DB (Command Mode):
Mongo DB (Command Mode):
Copy: C:\Program Files\MongoDB\mongosh-2.3.2-win32-x64\bin
Edit Environmental variable
Mongo DB (Command Mode):
Mongo DB (Command Mode):
Show dbs
Mongo DB (Command Mode):
Use mydb
Mongo DB (Command Mode):
Show collections
Mongo DB (Command Mode):
Open and View the data
User Accounts:
• User accounts are created to manage database access, control privileges, and provide security.
• MongoDB supports a role-based access control (RBAC) system, which allows administrators to assign specific permissions to users based on
their roles.
Create a new user: You can create users with different roles and permissions depending on what access they need.
Here’s an example to create a user: [Link]()
Common Roles in MongoDB:
• read: Grants read-only access to a specific database.
• readWrite: Grants read and write access to a specific database.
• dbAdmin: Provides administrative privileges for managing the database.
• userAdmin: Allows managing users and roles
Authenticating Users:
• Once user accounts are created, authentication is necessary for performing operations.
• MongoDB uses the following command to authenticate users: [Link]()
List all users in a database: You can list the users created for a specific database using [Link]()
• Delete a user: To remove a user from the database: [Link](“csk”)
Summary:
1. Connect to MongoDB:
First, access the MongoDB shell using the mongosh command.
2. Switch to the admin Database:
MongoDB users are usually created in the admin database, which allows managing users across the system.
3. Create a New User:
Use the [Link]() command to create a new user account. You will need to define the user’s username, password, and role.
4. Verify the User:
After creating the user, you can verify the list of users in the database.
5. Authenticate the User:
To log in with the new user, you need to authenticate with the following command: [Link]()
Access Control:
Access control in MongoDB refers to the mechanisms used to restrict who can access the database and what actions they are allowed to perform.
MongoDB provides a Role-Based Access Control (RBAC) system that allows you to define users and assign them roles that dictate the operations they can
execute.
Key Concepts in MongoDB Access Control:
1. Authentication: Authentication verifies the identity of users trying to access the MongoDB database. MongoDB supports multiple authentication mechanisms,
such as:
1. Username and password
2. Kerberos authentication – N/W
2. Authorization: Authorization defines what a user can do once they have authenticated. MongoDB’s authorization system uses roles to specify the operations a
user can perform on different resources.
Built-in Roles: MongoDB provides several predefined roles such as:
read: Grants permission to read data from a database.
readWrite: Grants permission to read and write data in a database.
dbAdmin: Provides database administration tasks like creating indexes or viewing statistics.
3. Roles and Privileges: Roles in MongoDB define a set of privileges that can be assigned to users.
Built-in Roles: These are predefined roles that come with MongoDB and cover common use cases.
read: Grants permission to read data from a database.
readWrite: Allows reading and writing data in a database.
dbAdmin: Provides administrative privileges for a specific database, including the ability to create and modify indexes and perform other administrative tasks.
Custom Roles: Administrators can create custom roles tailored to specific needs. This is useful when the built-in roles do not fully meet the requirements of an
application or organization.
Privileges determine the specific actions that a role can perform.
They can include operations like:
> find: Read documents in a collection. > insert: Add new documents to a collection.
> update: Modify existing documents. > remove: Delete documents from a collection.
> create Collection: Create new collections in a database.
4. Enabling Access Control: To enable access control in MongoDB
5. Auditing: MongoDB provides an auditing framework to track access to resources and operations performed by users.
Administering databases:
• Installation and Configuration
• User Access control
Database:
• Create database
• Displaying all the databases
• Drop database
Managing collections:
• Create Collections
• Display Collections
• Various CRUD Operations
• Drop Collections