0% found this document useful (0 votes)
18 views17 pages

Unit 2 (MongoDB)

NoSQL databases are designed to efficiently manage large volumes of diverse data types without a predefined schema, offering features like horizontal scalability and high performance. The document provides a detailed guide on installing and configuring MongoDB on Windows, including steps for starting the server and performing CRUD operations. It also covers indexing, querying, and data modeling strategies in MongoDB, emphasizing the flexibility of its document-oriented data model.

Uploaded by

Harsh Kumar
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)
18 views17 pages

Unit 2 (MongoDB)

NoSQL databases are designed to efficiently manage large volumes of diverse data types without a predefined schema, offering features like horizontal scalability and high performance. The document provides a detailed guide on installing and configuring MongoDB on Windows, including steps for starting the server and performing CRUD operations. It also covers indexing, querying, and data modeling strategies in MongoDB, emphasizing the flexibility of its document-oriented data model.

Uploaded by

Harsh Kumar
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
You are on page 1/ 17

Introduction to NoSQL Databases

NoSQL databases are a category of database systems designed to handle and


store large volumes of structured, semi-structured, or unstructured data in ways
that relational databases (SQL databases) cannot efficiently manage. The term
"NoSQL" stands for "Not Only SQL," indicating that these databases can handle
diverse data types and querying methods.

Key Features of NoSQL Databases


1. Schema Flexibility:
 Unlike traditional relational databases, NoSQL databases do not
require a predefined schema. This makes them ideal for dynamic,
unstructured, or rapidly changing data.
2. Horizontal Scalability:
 Designed to scale out by distributing data across multiple servers,
making them well-suited for handling big data and high-traffic
applications.
3. High Performance:
 Optimized for fast data reads and writes, making them suitable for
real-time applications.
4. Distributed Architecture:
 NoSQL databases are inherently distributed, ensuring data availability
and fault tolerance across multiple nodes.
5. Varied Data Models:
 Support different types of data models, enabling better adaptability
to specific application needs.

Installing and Configuring MongoDB


Here’s a detailed step-by-step guide to install and configure MongoDB on a
Windows system.

1. Download MongoDB
1. Visit the MongoDB Community Edition Download Page.
2. Select the appropriate version for Windows and download the .msi installer.

2. Install MongoDB
1. Run the Installer:
 Double-click the downloaded .msi file to launch the setup wizard.
2. Choose Setup Type:
 Select "Complete" to install all features, including the MongoDB
server and tools like mongosh.
3. Service Configuration:
 Choose to run MongoDB as a Windows service (recommended).
 Specify the data directory (default is C:\Program
Files\MongoDB\Server\<version>\bin).
4. Install Compass (Optional):
 During installation, you can opt to install MongoDB Compass, a
graphical interface for MongoDB.
5. Complete the Installation:
 Click "Install" to proceed. After the installation is complete, MongoDB
will be available on your system.

3. Configure MongoDB
Create Data and Log Directories
MongoDB requires specific directories to store data and logs:
1. Open File Explorer and create the following directories:
 Data Directory: C:\data\db
 Log Directory: C:\data\log
Create a Log File
1. Create an empty file mongod.log in C:\data\log.

4. Start MongoDB
Option 1: Using Command Prompt
1. Open a command prompt.
2. Navigate to the MongoDB installation directory (e.g., C:\Program
Files\MongoDB\Server\<version>\bin).
3. Start the MongoDB server:
mongod --dbpath "C:\data\db" --logpath "C:\data\log\mongod.log" --logappend --
port 27017
Option 2: Run as a Windows Service
1. By default, MongoDB is installed as a service and starts automatically.
2. You can manually manage the service:
 Start: net start MongoDB
 Stop: net stop MongoDB

5. Add MongoDB to System PATH


1. Add the bin folder of the MongoDB installation directory to the Windows
PATH:
 Example: C:\Program Files\MongoDB\Server\<version>\bin
2. This allows you to use MongoDB commands (mongod, mongosh) from any
command prompt.

6. Test MongoDB Installation


1. Open a command prompt.
2. Run the MongoDB shell:
mongosh
3. Verify the connection by running basic commands:
show dbs;
use testDB;
db.testCollection.insertOne({ name: "Test", type: "example" });
db.testCollection.find();

7. Optional Configuration
Edit MongoDB Configuration File
1. Locate mongod.cfg (default: C:\Program
Files\MongoDB\Server\<version>\bin\mongod.cfg).
2. Open it in a text editor and modify key settings as needed:
 Bind IP Address: Allow MongoDB to accept remote connections:
net:
bindIp: 0.0.0.0
 Port: Change the default port (27017) if required:
net:
port: 27017
 Enable Authentication: Secure your database:
security:
authorization: enabled
3. Restart the MongoDB service for changes to take effect:
net stop MongoDB
net start MongoDB

8. Access MongoDB via MongoDB Compass (Optional)


 If MongoDB Compass was installed:
 Open MongoDB Compass.
 Connect to the server (default: localhost:27017).

By following these steps, MongoDB will be installed and configured on your


Windows system, ready for development or production use.

CRUD Operations in MongoDB


CRUD stands for Create, Read, Update, and Delete—the fundamental operations
for interacting with any database. In MongoDB, these operations are performed
on collections (analogous to tables in relational databases) and documents
(analogous to rows in relational databases).
Here’s a breakdown of how to perform CRUD operations using the MongoDB shell
(mongosh) or any MongoDB client.

1. 1. Create Operations
Create operations add new documents to a collection.
Insert a Single Document
db.collection.insertOne({ name: "John", age: 25, city: "New York" });
Insert Multiple Documents
db.collection.insertMany([ { name: "Alice", age: 30, city: "London" },
{ name: "Bob", age: 22, city: "Paris" }
]);

2. Read Operations
Read operations retrieve data from collections.
Find All Documents
db.collection.find();
Find Documents with a Query
Use a query object to filter results:
db.collection.find({ city: "New York" });
Find One Document
db.collection.findOne({ name: "John" });
Format Output (Pretty Print)
db.collection.find().pretty();
Projection (Select Specific Fields)
db.collection.find({ city: "London" }, { name: 1, age: 1, _id: 0 });

3. Update Operations
Update operations modify existing documents.
Update a Single Document
db.collection.updateOne(
{ name: "John" }, // Filter
{ $set: { age: 26 } } // Update
);
Update Multiple Documents
db.collection.updateMany( { city: "London" }, // Filter
{ $set: { country: "UK" } } // Update
);
Replace a Document
Replace an entire document:
db.collection.replaceOne( { name: "Alice" }, // Filter
{ name: "Alice", age: 35, city: "Berlin" } // New document
);

4. Delete Operations
Delete operations remove documents from collections.
Delete a Single Document
db.collection.deleteOne({ name: "John" });
Delete Multiple Documents
db.collection.deleteMany({ city: "London" });
Drop an Entire Collection
Remove all documents and the collection itself:
db.collection.drop();

CRUD Operations Example


Let’s see an example that combines all four operations:
Step 1: Insert Documents

db.users.insertMany([
{ name: "Emma", age: 28, city: "New York" },
{ name: "Liam", age: 35, city: "London" },
{ name: "Sophia", age: 22, city: "Paris" }
]);
Step 2: Read Documents
db.users.find();
Step 3: Update Documents
db.users.updateOne({ name: "Emma" }, { $set: { age: 29 } });
Step 4: Delete a Document
db.users.deleteOne({ name: "Sophia" });

CRUD Operations Using Drivers


If you're using MongoDB drivers (e.g., Python, Node.js), CRUD operations are
performed similarly by calling corresponding methods
like insert_one, find, update_one, and delete_one on the collection object. Let me
know if you’d like specific examples for a programming language!

Indexing and Querying in MongoDB


Indexing and querying are fundamental features in MongoDB that help retrieve
and manage data efficiently. Here's a detailed guide on how they work and how to
implement them.
1. Indexing in MongoDB
Indexes are special data structures that store a small portion of the collection's
data in an easy-to-traverse format. They improve the speed of query execution.
Default Index
 MongoDB automatically creates an _id index for every document, which
ensures uniqueness and fast lookups based on the _id field.
Types of Indexes
1. Single Field Index:
 Creates an index on a single field.
db.collection.createIndex({ fieldName: 1 }); // 1 for ascending, -1 for descending
2. Compound Index:
 Creates an index on multiple fields.
db.collection.createIndex({ field1: 1, field2: -1 });
3. Multikey Index:
 Indexes array fields.
db.collection.createIndex({ arrayField: 1 });
4. Text Index:
 Enables text search for strings.
db.collection.createIndex({ fieldName: "text" });
5. Geospatial Index:
 Used for querying geographical coordinates.
db.collection.createIndex({ location: "2dsphere" });
6. Unique Index:
 Ensures all indexed values are unique.
db.collection.createIndex({ fieldName: 1 }, { unique: true });
7. TTL (Time-to-Live) Index:
 Automatically removes documents after a specified period.
db.collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });

Managing Indexes
1. View Indexes:
db.collection.getIndexes();
2. Drop an Index:
db.collection.dropIndex("indexName");
3. Drop All Indexes:
db.collection.dropIndexes();

2. Querying in MongoDB
MongoDB provides a flexible query language for retrieving data. Queries are
performed using the find() method.
Basic Queries
1. Find All Documents:
db.collection.find();
2. Find with Filters:
db.collection.find({ fieldName: value });
3. Find Specific Fields (Projection):
db.collection.find({ fieldName: value }, { field1: 1, field2: 0 }); // 1 to include, 0 to
exclude

1. Query Operators
1. Comparison Operators:
db.collection.find({ age: { $gt: 18 } }); // Greater than
db.collection.find({ age: { $gte: 18 } }); // Greater than or equal
db.collection.find({ age: { $lt: 30 } }); // Less than
db.collection.find({ age: { $lte: 30 } }); // Less than or equal
db.collection.find({ age: { $ne: 25 } }); // Not equal
db.collection.find({ age: { $in: [18, 25, 30] } }); // In array
db.collection.find({ age: { $nin: [18, 25] } }); // Not in array
2. Logical Operators:
db.collection.find({ $and: [{ age: { $gt: 18 } }, { city: "London" }] });
db.collection.find({ $or: [{ age: { $lt: 18 } }, { city: "Paris" }] });
db.collection.find({ $not: { age: { $gte: 18 } } });
3. Element Operators:
db.collection.find({ fieldName: { $exists: true } }); // Field exists
db.collection.find({ fieldName: { $type: "string" } }); // Field is of type
4. Array Operators:
db.collection.find({ tags: { $all: ["tag1", "tag2"] } }); // Match all elements
db.collection.find({ tags: { $size: 2 } }); // Array size
db.collection.find({ tags: { $elemMatch: { key: "value" } } }); // Match specific
element
5. Regular Expressions:
db.collection.find({ name: /john/i }); // Case-insensitive search

2. Sorting, Limiting, and Skipping


1. Sort Results:
db.collection.find().sort({ age: 1 }); // 1 for ascending, -1 for descending
2. Limit Results:
db.collection.find().limit(5);
3. Skip Results:
db.collection.find().skip(5);
4. Combine Sort, Limit, and Skip:
db.collection.find().sort({ age: -1 }).limit(5).skip(10);

Schema Design in MongoDB


1. Application Requirements:
 Understand the application's query patterns, data relationships, and
performance needs.
2. Read vs. Write Optimization:
 Decide whether the schema should prioritize faster reads
(denormalization) or writes (normalization).
3. Data Relationships:
 Consider how entities are related and whether to
use embedding or referencing.
4. Data Growth and Scalability:
 Plan for scaling as the dataset grows, ensuring efficient sharding and
indexing.
5. Data Structure and Access Patterns:
 Optimize the schema based on how the data will be queried and
updated.
Data Modeling in MongoDB
Data modeling in MongoDB involves designing the structure of your data to meet
the application's performance, scalability, and functionality requirements. Unlike
relational databases, MongoDB uses a flexible, document-based schema that can
handle unstructured or semi-structured data efficiently.

Key Concepts in MongoDB Data Modeling

Document-Oriented Data Model

 MongoDB uses documents (key-value pairs) as the basic unit of data.


 Documents can be nested (hierarchical) and contain arrays, unlike rows in
relational databases.
 Example of a document for a blog post:

json
{
"_id": 1,
"title": "Introduction to MongoDB",
"author": { "name": "John", "email":
"[email protected]" },
"tags": ["MongoDB", "Database", "NoSQL"],
"comments": [
{ "user": "Jane", "comment": "Great
article!" },
{ "user": "Doe", "comment": "Very helpful,
thanks!" }
]
}

2. Schema Design in MongoDB

MongoDB is schema-less, meaning documents in a collection do not require a


predefined structure. However, defining a schema helps ensure data consistency.

 Flexible Schema: You can add new fields to documents without affecting
other documents in the collection.
 Example:

json
// Document 1
{ "name": "Alice", "age": 25 }

// Document 2 (with additional fields)


{ "name": "Bob", "age": 30, "address": "New York" }

3. Embedding vs. Referencing Relationships

MongoDB allows you to represent relationships between data in two main ways:

a) Embedded Data (Denormalized)

 Store related data inside the parent document as a subdocument.


 Suitable for one-to-few relationships where child data is always accessed
with the parent.
 Example:

json
{
"name": "Product A",
"category": "Electronics",
"reviews": [
{ "user": "Alice", "rating": 5 },
{ "user": "Bob", "rating": 4 }
]
}

b) Referenced Data (Normalized)

 Store related data in separate collections and reference them using foreign
keys.
 Suitable for one-to-many or many-to-many relationships.
 Example:
o Products Collection:

json
{ "_id": 1, "name": "Product A", "category":
"Electronics" }

o Reviews Collection:

json
Copy code
{ "product_id": 1, "user": "Alice", "rating":
5 }
{ "product_id": 1, "user": "Bob", "rating": 4 }

4. Data Modeling Strategies

a. One-to-One Relationship

 Embed the related document inside the parent document.


 Example:

json
{
"user_id": 1,
"name": "John",
"profile": { "email": "[email protected]", "age":
30 }
}

b. One-to-Many Relationship

 Embed for small datasets: Store subdocuments in an array.


 Reference for large datasets: Use a separate collection.
 Example (embedded):

json
Copy code
{
"post_id": 1,
"title": "MongoDB Guide",
"comments": [
{ "user": "Alice", "comment": "Great!" },
{ "user": "Bob", "comment": "Thanks!" }
]
}

c. Many-to-Many Relationship

 Use referencing to connect documents in two collections.


 Example:
o Users Collection:

json
{ "_id": 1, "name": "Alice" }

o Courses Collection:

json
Copy code
{ "_id": 101, "course_name": "MongoDB Basics" }

o Enrollment Collection:

json
Copy code
{ "user_id": 1, "course_id": 101 }

5. Aggregation Framework

MongoDB’s Aggregation Framework allows you to process and transform data


in collections.

 You can use operators like $group, $match, $lookup, and $unwind.
 Example: Join referenced data using $lookup for a many-to-many
relationship.

6. Data Redundancy

 In MongoDB, it is sometimes acceptable to duplicate data to improve query


performance.
 Redundancy reduces the need for joins, which can be expensive in NoSQL
databases.

You might also like