Mongidb 1
Mongidb 1
Chapter 1
Introduction to MongoDB
Introduction to MongoDB
MongoDB is a powerful, open-source, NoSQL (Not Only SQL) database management system
designed to handle large volumes of unstructured data. Developed by MongoDB Inc. and first
released in 2009, it provides a high-performance, scalable, and flexible alternative to traditional
relational databases such as MySQL or PostgreSQL. MongoDB is widely adopted in modern web,
mobile, and cloud-based applications due to its ease of use, rich feature set, and robust support for
modern development environments.
1. Document-Oriented Storage:
Unlike relational databases that store data in tables and rows, MongoDB stores data in
flexible, JSON-like documents (in BSON format). Each document can have a different
structure, allowing more flexibility in representing complex data models.
2. Schema-less Design:
MongoDB collections do not enforce a strict schema, enabling developers to modify the
structure of documents without affecting existing data. This feature is particularly useful in
agile and rapidly changing development environments.
3. Scalability:
MongoDB supports horizontal scaling through a technique known as sharding, which allows
the database to distribute data across multiple servers or nodes. This ensures the application
can handle massive amounts of data and high throughput demands.
4. High Performance:
MongoDB delivers high read and write throughput due to its efficient data storage and
indexing mechanisms. It supports in-memory computing, indexing, and aggregation pipelines
for fast and efficient data processing.
5. Rich Query Language:
MongoDB provides a powerful and expressive query language that supports CRUD (Create,
Read, Update, Delete) operations, as well as advanced features such as filtering, sorting, joins
(via $lookup), and aggregation.
6. Built-in Replication:
MongoDB ensures data availability and fault tolerance through replica sets, which are groups
of MongoDB servers that maintain the same data set. If the primary server fails, one of the
secondary servers automatically takes over.
7. Integration with Modern Applications:
MongoDB has drivers for all major programming languages including Python, JavaScript
(Node.js), Java, C#, and more. It integrates well with modern frameworks and cloud
platforms, making it an excellent choice for web and mobile development.
Architecture Overview
MongoDB's architecture revolves around the following core components:
MongoDB stores data in a binary format called BSON (Binary JSON), which extends the JSON
format with additional data types like date, int, and decimal.
Advantages of MongoDB
Chapter 2
1. Structure of a Document
A typical MongoDB document looks like this:
json
Copy code
{
"_id": "12345",
"name": "Alice Smith",
"email": "[email protected]",
"age": 29,
"address": {
"street": "123 Main Street",
"city": "New York",
"zip": "10001"
},
"hobbies": ["reading", "traveling", "coding"]
}
This document:
This hierarchy allows for high flexibility and efficient organization of data.
d. Performance
By storing all related data in a single document, MongoDB reduces the number of read operations.
This results in faster queries and efficient data retrieval, especially for read-heavy workloads.
Use embedding when data is accessed together frequently and doesn’t grow unbounded
(e.g., user profile and preferences).
Use referencing when data is large, shared across documents, or updated frequently (e.g.,
product catalog and orders).
Avoid excessive nesting and large arrays that can slow down query performance.
Relational Model:
json
Copy code
{
"username": "blogger101",
"email": "[email protected]",
"posts": [
{
"title": "Introduction to NoSQL",
"content": "NoSQL databases offer...",
"comments": [
{ "user": "reader1", "text": "Great post!" },
{ "user": "reader2", "text": "Very helpful, thanks!" }
]
}
]
}
This example illustrates how embedding posts and comments into a single document can simplify
the data model and enhance performance.
Chapter 3
Connecting to a MongoDB Database
Establishing a connection to a MongoDB database is a crucial step in developing any application
that relies on MongoDB for data storage and retrieval. MongoDB supports various connection
methods, depending on whether the database is hosted locally or on a cloud platform such as
MongoDB Atlas. The connection process typically involves using a MongoDB connection URI,
which contains the necessary credentials and configuration to link an application to the database
server.
php-template
Copy code
mongodb://<username>:<password>@<host>:<port>/<database>?options
For example, connecting to a local MongoDB database might use:
bash
Copy code
mongodb://localhost:27017/mydatabase
In a cloud environment like MongoDB Atlas, the URI would look like:
bash
Copy code
mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority
This format enables secure, customizable, and scalable access to the database from any compatible
client or programming language.
# Establish connection
client = MongoClient("mongodb://localhost:27017/")
# Access a database
db = client["mydatabase"]
# Access a collection
collection = db["users"]
# Insert a document
collection.insert_one({"name": "Alice", "email": "[email protected]"})
Using Node.js (with Mongoose):
javascript
Copy code
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.once('open', () => {
console.log("Connected to MongoDB successfully");
});
Example in Python:
python
Copy code
from pymongo import MongoClient
uri = "mongodb+srv://user123:[email protected]/mydatabase?retryWrites=true&w=majority"
client = MongoClient(uri)
db = client["mydatabase"]
Python Example:
python
Copy code
print(client.list_database_names())
Node.js Example:
javascript
Copy code
db.listCollections().toArray((err, collections) => {
console.log(collections);
});
Chapter 4
MongoDB CRUD Operations
In MongoDB, CRUD stands for Create, Read, Update, and Delete, which are the fundamental
operations performed on data in a database. Among these, the Insert (Create) and Find (Read)
operations are the most basic and frequently used in applications that interact with MongoDB.
MongoDB uses a document-oriented model, where data is stored in flexible, JSON-like documents
inside collections. These operations are performed using built-in methods provided by MongoDB
drivers or the MongoDB shell.
a. insertOne()
This method inserts a single document into a collection.
Syntax:
javascript
Copy code
b. insertMany()
This method inserts multiple documents at once.
Example:
javascript
Copy code
db.students.insertMany([
{ name: "Alice", age: 21, course: "Electronics" },
{ name: "Bob", age: 23, course: "Mechanical" }
])
This adds two new documents to the students collection. Using insertMany() is efficient for bulk insert
operations.
a. find()
This method retrieves documents that match the specified query criteria.
Syntax:
javascript
Copy code
db.collection.find(query)
Example 1: Find All Documents
javascript
Copy code
db.students.find()
This returns all documents from the students collection.
b. findOne()
This method returns the first document that matches the query condition.
Example:
javascript
Copy code
db.students.find({ age: 22 }, { name: 1, _id: 0 })
This returns only the name field (excluding _id) for all students aged 22.
client = MongoClient("mongodb://localhost:27017/")
db = client["university"]
collection = db["students"]
Chapter 5
MongoDB CRUD Operations
MongoDB provides comprehensive support for CRUD operations: Create, Read, Update, and
Delete. After inserting and retrieving data using insert and find, developers often need to replace
existing documents or delete them entirely. MongoDB offers various methods for these tasks,
allowing for powerful and flexible data management.
filter:
The condition used to match the document to replace.
replacement: The new document that will replace the existing one.
Example:
javascript
Copy code
db.students.replaceOne(
{ name: "John Doe" },
{ name: "John Doe", age: 23, course: "Data Science" }
)
In this example, MongoDB searches the students collection for a document where name is "John Doe"
and replaces it entirely with a new document containing updated age and course values. If the matched
document had other fields, they are lost unless included in the replacement.
a. deleteOne()
This method deletes the first document that matches the given condition.
Syntax:
javascript
Copy code
db.collection.deleteOne(filter)
Example:
javascript
Copy code
db.students.deleteOne({ name: "Alice" })
This command deletes the first document in the students collection where the name field is "Alice".
b. deleteMany()
This method deletes all documents that match the specified filter.
Syntax:
javascript
Copy code
db.collection.deleteMany(filter)
Example:
javascript
Copy code
db.students.deleteMany({ course: "Mechanical" })
This deletes all documents where the course is "Mechanical" from the students collection.
client = MongoClient("mongodb://localhost:27017/")
db = client["university"]
collection = db["students"]
collection.replace_one(
{"name": "John Doe"},
{"name": "John Doe", "age": 24, "course": "Artificial Intelligence"}
)
Delete Example:
python
Copy code
# Delete a single document
collection.delete_one({"name": "Alice"})
4. Important Considerations
Backup Before Replacement or Deletion: Since both replaceOne() and deleteMany() can result
in permanent data loss, it is advisable to back up data before executing these operations.
Use with Caution: Especially deleteMany(), as it can affect a large number of documents.
Atomicity: These operations are atomic at the document level, meaning each replacement or
deletion happens in isolation.
Chapter 6
MongoDB CRUD Operations
In MongoDB, after performing read operations using methods like find() or findOne(), it is often
necessary to modify the query results to suit the requirements of the application or user. MongoDB
provides several features to modify, filter, limit, sort, and project data during retrieval. These
modifications do not change the data in the database; instead, they shape the output returned by the
query.
Syntax:
javascript
Copy code
db.collection.find(query, projection)
1 includes a field.
0 excludes a field.
Example:
javascript
Copy code
db.students.find({ course: "IT" }, { name: 1, _id: 0 })
This returns only the name field (excluding _id) of students enrolled in the IT course.
Syntax:
javascript
Copy code
db.collection.find().sort({ field: 1 }) // Ascending
db.collection.find().sort({ field: -1 }) // Descending
Example:
javascript
Copy code
db.students.find().sort({ age: -1 })
This query returns all student documents sorted in descending order of their age.
Syntax:
javascript
Copy code
db.collection.find().limit(n)
Example:
javascript
Copy code
db.students.find().limit(5)
This returns the first 5 documents from the students collection.
Syntax:
javascript
Copy code
db.collection.find().skip(n)
Example:
javascript
Copy code
db.students.find().skip(5).limit(5)
This skips the first 5 documents and returns the next 5 documents.
5. Combining Methods
All the above methods can be combined for advanced querying and result formatting.
Example:
javascript
Copy code
db.students.find(
{ course: "Computer Science" },
{ name: 1, age: 1, _id: 0 }
).sort({ age: 1 }).skip(2).limit(3)
This query:
Chapter 7
MongoDB CRUD Operations: Insert and Find Documents
1. Inserting Documents
To add new documents to a collection, MongoDB provides the insertOne() and insertMany()
methods.
Syntax:
db.collection.insertOne(document)
Example:
db.students.insertOne({
age: 21,
course: "CSE"
})
This command inserts a new student document into the students collection.
db.students.insertMany([
])
2. Finding Documents
Syntax:
db.collection.find(query)
db.collection.findOne(query)
Examples:
Inserting Documents:
db.students.insert_one({
"age": 21,
"course": "CSE"
})
db.students.insert_many([
])
Finding Documents:
students = db.students.find()
print(student)
print(student)
Chapter 8
MongoDB CRUD Operations: Replace and Delete Documents
Dept. of CS&E, MIT Mysore 2024-2025 18
Introduction To MongoDB
MongoDB supports replacing and deleting documents as part of its core CRUD operations. These
operations are useful for updating an entire document or removing one or more documents that
match specific criteria.
1. Replacing Documents
The replaceOne() method is used to replace a single document that matches a specified filter with a
completely new document. It does not perform a partial update; the existing document is fully
replaced.
Syntax:
db.collection.replaceOne(filter, replacement)
Example:
db.students.replaceOne(
{ name: "John" },
This command finds the first document where name is "John" and replaces the entire document with
the new one provided.
2. Deleting Documents
MongoDB provides two methods to delete documents from a collection: deleteOne() and
deleteMany().
Syntax:
db.collection.deleteOne(filter)
db.collection.deleteMany(filter)
Examples:
Replacing a Document:
db.students.replace_one(
{ "name": "John" },
Deleting a Document:
Chapter 9
MongoDB CRUD Operations: Modifying Query Results
Dept. of CS&E, MIT Mysore 2024-2025 20
Introduction To MongoDB
After retrieving data using the find() or findOne() methods, MongoDB allows the results to be
refined using various modifiers. These operations are useful for filtering fields, sorting output,
paginating results, and shaping the final result set. It’s important to note that these modifications do
not alter the actual documents in the database — they only affect the result of the query.
1. Projection
Projection is used to include or exclude specific fields from the documents in the query result.
Syntax:
db.collection.find(query, projection)
Example:
This returns only the name field (excluding _id) of students enrolled in the IT course.
Syntax:
Example:
db.students.find().sort({ age: -1 })
Syntax:
db.collection.find().limit(n)
Example:
db.students.find().limit(5)
4. Skipping Documents
Syntax:
db.collection.find().skip(n)
Example:
db.students.find().skip(5).limit(5)
5. Combining Methods
All of the above methods can be combined for advanced querying and formatting of results.
Example:
db.students.find(
This query:
Projection:
print(student)
Sorting:
students = db.students.find().skip(5).limit(10)
Chapter 10
MongoDB Aggregation
Dept. of CS&E, MIT Mysore 2024-2025 22
Introduction To MongoDB
Aggregation in MongoDB is the process of transforming and combining data from multiple
documents into a summarized result. MongoDB’s Aggregation Framework is analogous to SQL’s
GROUP BY and supports advanced operations using a pipeline-based approach.
1. Aggregation Pipeline
The aggregation pipeline is a series of stages. Each stage takes input documents, processes them, and
passes the result to the next stage.
db.collection.aggregate([
{ stage1 },
{ stage2 },
...
])
6. Use Cases
- Generating reports and summaries
- Analyzing sales or student performance
- Performing real-time analytics
Indexes in MongoDB enhance query performance by allowing fast lookups. Without indexes,
MongoDB must scan each document in a collection (a full collection scan).
1. Types of Indexes
Single Field – Index on one field.
Compound – Index on multiple fields.
Multikey – Index on arrays.
Text – Supports full-text search.
Hashed – Used for sharding.
TTL – Automatically deletes documents after a period.
2. Creating Indexes
db.students.createIndex({ name: 1 }) // Ascending
db.students.createIndex({ age: -1 }) // Descending
4. TTL Index
db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
7. Python Example
collection.create_index([("name", 1)])
collection.drop_index("name_1")
8. Best Practices
- Create indexes for fields used in queries, sorting, or filtering.
- Avoid too many indexes—they can slow down writes.
4. Autocomplete Example
db.products.aggregate([
{
$search: {
autocomplete: {
query: "lap",
path: "productName"
}
}
}
])
6. Highlighting Matches
db.articles.aggregate([
{
$search: {
index: "default",
text: {
query: "cloud",
path: "content"
}
}
},
{
$project: {
title: 1,
content: 1,
highlights: { $meta: "searchHighlights" }
}
}
])
7. Search Metadata
db.students.aggregate([
{
$searchMeta: {
text: {
query: "AI",
path: "course"
}
8. Best Practices
- Use dynamic mappings for quick setup.
- Fine-tune scoring and filters for performance.
- Combine $search with $project, $sort, and $limit for better UX.
CONCLUSION
This internship not only strengthened my understanding of how modern databases operate but also
enhanced my skills in managing and querying unstructured data effectively. By working with real-
world use cases and examples, I developed practical knowledge that is crucial for building scalable
and high-performance web applications. Overall, the internship has significantly boosted my
confidence in using MongoDB as a robust backend solution and has equipped me with essential
database skills for my future career in software development.