0% found this document useful (0 votes)
2 views39 pages

NoSQL - MongoDB

Uploaded by

rajiv.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)
2 views39 pages

NoSQL - MongoDB

Uploaded by

rajiv.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

Agenda

• NoSQL Databases – What and Why?


• MongoDB- Introduction
• MongoDB- Features
• MongoDB – Datatypes
• MongoDB – Query Language (CRUD Operations)
NoSQL Databases – What and Why?
• NoSQL (“not only SQL”) databases are non-relational, distributed
data management system designed for flexibility, scalability, and
high performance with large volumes of unstructured or rapidly
changing data.
• They are used to handle massive, diverse datasets (Big Data).
• Enable agile development with flexible schemas.
• Scale horizontally across servers.
NoSQL Databases – Common Types
• Document Databases (e.g., MongoDB): Store data in JSON-like
formats.
• Key-Value Stores (e.g., Redis): Ideal for caching and session
management.
• Wide-Column Stores (e.g., Cassandra): Optimized for large-scale
data queries.
• Graph Databases (e.g., Neo4j): Ideal for analyzing relationships.
MongoDB- Introduction
• MongoDB is a leading NoSQL, open-source, document-oriented
database designed for high performance, high availability, and
easy scalability.
• Unlike traditional relational databases that store data in tables
and rows, MongoDB stores data in flexible, JSON-like documents.
• In the Big Data era, the "3 Vs" (Volume, Velocity, and Variety) made
rigid SQL schemas a bottleneck.
• MongoDB addresses this by being schema-less, meaning documents in
the same collection do not need to have the same set of fields.
RDMS vs MongoDB

Concept RDBMS (SQL) MongoDB (NoSQL)

Storage Unit Table / Row Collection / Document

Schema Fixed / Pre-defined Dynamic / Flexible

Relationships Joins Embedded Documents / Linking

Scaling Vertical (Bigger Server) Horizontal (Sharding)

ACID (Single Document & Multi-


Transaction ACID compliant
doc)
MongoDB - Features
• Auto Sharding
• Automatic data distribution across multiple
servers.
• Enables horizontal scaling.
• Handles large datasets efficiently.
• Example - Social media app distributes
users across servers.
• Document Oriented
• Stores data in JSON-like documents
(BSON).
• Flexible schema.
• No fixed table structure.
• Example - { "name": "Raj", "skills": ["Python",
"MongoDB"] }
•.
• High Performance
• Fast read/write operations.
• Uses indexing
• Memory-efficient storage
• Example - E-commerce site fetching
products instantly.
• Fast In-place Updates
• Updates only specific fields
• Reduces overhead
• Improves speed
• Example - { "$set": { "age": 26 } }
Mongo DB – Data Types
• String – stores data in BSON string format. MongoDB driver
automatically handles the conversion between the programming
language string type and BSON. All strings stores in MongoDB
must be utf-8.
• Example:
[Link]([{ "_id":
ObjectId("6009585d35cce6b7b8f087f1"),
"title": "Math",
"author": "Alen",
"level": "basic", "length": 230, "example": 11 },
Mongo DB – Data Types
• Integer - We can store integer data type in two forms 32-bit signed
integer and 64-bit signed integer. Used to store whole numbers, such
as ages, counts, or any other numerical data that doesn't require
decimal points.
• Example:
[Link]([{ "_id":
ObjectId("6009585d35cce6b7b8f087f1"),
"title": "Math",
"author": "Alen",
"level": "basic",
"length": 230, "example": 11 },
Mongo DB – Data Types
• Double - Used for storing floating-point numbers (decimal values).
Commonly used for storing data that requires decimal precision, such
as prices, percentages, or scores
• Example:
[Link]([{ "_id":
ObjectId("6009585d35cce6b7b8f087f1"),
"title": "Math",
"author": "Alen",
"level": "basic",
“age": 23.5,
“percentage": 11.67 },
Mongo DB – Data Types
• Boolean – true/false
• null
• Array - MongoDB arrays can contain values of the same or
different data types. Array is created using square brackets([]).
For example: “Skills”: [“C”, “Python”]
• Object - Object data type stores embedded documents.
Embedded documents are also known as nested
documents. Embedded documents allow us to structure our data
hierarchically, which is useful for representing more complex data
models.
Mongo DB – Data Types
• Object - Object data type stores embedded documents.
Embedded documents are also known as nested
documents. Embedded documents allow us to structure our data
hierarchically, which is useful for representing more complex data
models.
MongoDB - CRUD
• Create- Create operations add new documents to a collection. If
the collection doesn't exist, MongoDB creates it automatically
upon the first insert.
Method Description Example
// Insert a single user
Inserts a single document [Link]({ name:
insertOne()
into a collection. "Alice", age: 28, skills: ["MongoDB",
"[Link]"], status: "active" });
// Insert multiple products
[Link]([ { item:
Inserts an array of multiple
insertMany() "Laptop", qty: 5, tags:
documents into a collection.
["electronics"] }, { item: "Mouse",
qty: 20, tags: ["peripherals"] } ]);
MongoDB - CRUD
Read - retrieve documents from a collection. You can use filters to
find specific data.
• MongoDB has two methods of reading documents from a
collection:
Method Description Example
// Find all users where age is
find(filter, Returns a cursor to documents
greater than 25 [Link]({
projection) matching the filter.
age: { $gt: 25 } });
// Find a specific user but only
return the 'name' field
findOne(fil Returns the first document that
(Projection) [Link]({
ter) matches the filter.
name: "Alice" }, { name: 1, _id: 0
});
• $eq – equal to
• $gt / $lt – Greater than and Less Than.
• $in – matches any of the values in array.

• $set - Replaces the value of a field.


• $inc - Increments a numeric value.
• $push - Adds an item to an array.
MongoDB - CRUD
Update - modify existing documents. They use a filter to find the
document and an update operator to change it.
Method Description Example
Updates the first // Update Alice's age to 29
updateOne() document that matches [Link]( { name: "Alice"
the filter. }, { $set: { age: 29 } } );
// Increment stock for all electronics
updateMany Updates all documents by 10 [Link]( {
() that match the filter. tags: "electronics" }, { $inc: { qty: 10 } }
);
[Link]( {“name”:
“John Doe”} ,
Replaces the entire
replaceOne() {“name”:”John Doe”,
document (except _id).
“position”:”Manager”, “age”:35,
MongoDB - CRUD
Delete - remove documents from a collection.

Method Description Example


Removes the first
// Delete the user named Alice
deleteOne() document that matches
[Link]({ name: "Alice" });
the filter.
// Delete all inactive users
deleteMany( Removes all documents
[Link]({ status:
) that match the filter.
"inactive" });
Update
• Modify existing documents. They use a filter to find the document
and an update operator to change it.
• [Link]([{ name: "Marsh", age: "6 years",
species: "Dog", ownerAddress: "380 W. Fir Ave", chipped: true},
{name: "Kitana", age: "4 years", species: "Cat",
ownerAddress: "521 E. Cortland", chipped: true}])

• [Link]({name: "Marsh"}, {$set:{ownerAddress:


"451 W. Coffee St. A204"}})[Link]()
Agenda Points
• Arrays Functions
• Count
• Sort
• Limit
• Skip
• Aggregate
• Map Reduce
• Cursors
• Mongo Import and Export
MongoDB - Arrays
• Creating
• Find Documents Containing a Specific Array Value
• [Link]({tags:'cloud’})
• Add Element to Array ($push)
• [Link]( { title: "Introduction to MongoDB" }, { $push: {
comments: {user:"Tajpreet",text:"Excellent explanation!" } }})
• Add Multiple Elements ($each)
• [Link]( { title: "Getting Started with [Link]" }, { $push: {
tags: { $each: ["backend", "runtime"] } } })
MongoDB - Arrays
• Remove Element from Array ($pull)
• [Link]( { title: "Introduction to MongoDB" }, { $pull: {
tags: "nosql" } } )
• Add Unique Element ($addToSet)
• [Link]( { title: "Introduction to MongoDB" }, { $addToSet: {
tags: "nosql" } })
• Remove First or Last Element ($pop)
• // Remove last element
• [Link]( { title: "Introduction to MongoDB" }, { $pop: {
comments: 1 } })
• // Remove first element
• [Link]( { title: "Introduction to MongoDB" }, { $pop: {
comments: -1 } })
MongoDB - Arrays
• Update Specific Array Element ($set with index)
• [Link]( { title: "Getting Started with [Link]" }, { $set: {
"comments.0": [{user:'James', text:'Updated comment' }] }})
• Find Documents Based on Array Size
• [Link]({ comments: { $size: 2 } })
• Use $elemMatch for Complex Queries
• [Link]({ tags: { $elemMatch: { $eq: "javascript" } }})
• Project Specific Array Fields
• [Link]( { title: "Introduction to MongoDB" }, { tags: 1, _id: 0 })
• Slice Array ($slice)
• [Link]( {}, { comments: { $slice: 1 } })
MongoDB - Arrays
• Count Documents Containing a Specific Array Value
• [Link]({ tags: "mongodb" })
• [Link]({ $or: [ { tags: "database" }, { tags: "iaas" }
]});
• Count Documents Where Array Size = Specific Number
• Count posts with exactly 2 comments:
• [Link]({ comments: { $size: 2 } })
• Count Documents Where Array Size > N
• Count posts having more than 2 likes
• [Link]({ comments: { $size: 2 } })
MongoDB - Arrays
• Count Total Number of Array Elements Across All Documents
• Count total comments in the entire collection:
• [Link]([ { $project: { count: { $size: "$comments" } } }, { $group: {
_id: null, totalComments: { $sum: "$count" } } }])
• Count Frequency of Each Tag
• Find popularity ranking.
• [Link]([ { $unwind: "$tags" }, { $group: { _id: "$tags", count: {
$sum: 1 } } }, { $sort: { count: -1 } }])
MongoDB – Arrays
• Sort Documents by Number of Comments (Descending)
• [Link]([ { $addFields: { commentCount: { $size:
"$comments" } } }, { $sort: { commentCount: -1 } }])
• Sort Documents by Number of Likes (Ascending)
• [Link]([ { $addFields: { likeCount: { $size: "$likes" } } },
{ $sort: { likeCount: 1 } }])
• Sort Array Elements Inside Document
• Sort tags alphabetically inside each document (ascending)
• [Link]( {}, [ { $set: { tags: { $sortArray: {
input: "$tags", sortBy: 1 } } } } ])
MongoDB – Arrays
• Sort Documents Based on First Element of Array
• [Link]().sort({ "tags.0": 1 })
• Sort After Unwinding Array
• Sort individual comments alphabetically:
• [Link]([ { $unwind: "$comments" }, { $sort: { comments: 1 }
}])
• Combined Count + Sort
• Top 3 most used tags
• [Link]([ { $unwind: "$tags" }, { $group: { _id: "$tags", total: {
$sum: 1 } } }, { $sort: { total: -1 } }, { $limit: 3 }])
Array – Limit Operation
• Limit Number of Documents
• Return only first 2 blog posts:
• [Link]().limit(2)
• Skip Documents
• Skip first 1 document
• [Link]().skip(1)
• Limit Results Where Array Contains Value
• [Link]({ tags: "mongodb" }).limit(2)
Array – Limit Operation
• Skip + Limit with Sorted Array Size
• Sort by number of comments, then paginate:
• [Link]([
• {
• $addFields: {
• commentCount: { $size: "$comments" }
• }
• },
• { $sort: { commentCount: -1 } },
• { $skip: 1 },
• { $limit: 2 }
• ])
Array – Limit Operation
• Limit Elements of an Array ($slice)
• Return only first 2 comments per document:
• [Link]( {}, { comments: { $slice: 2 }, title: 1 })
• Skip first 1 comment and return next 2:
Aggregate
• In MongoDB, performing aggregate functions on arrays typically
involves a few key stages (Aggregate Pipeline).
• Since arrays are nested structures, you usually need to "break
them open" or use specific operators to treat the array elements
as individual data points.
• Common ways:
• Using $unwind – want to use standard accumulators like $sum, $avg, or
$max , then deconstruct array.
• Flattens the array, creating a separate document for each element-
$unwind
• Re-aggregates the documents to calculate your value - $group
Aggregation
• Practice
• [Link]
examples/

• In MapReduce, you define two JavaScript functions:


• Map: Emits key-value pairs (e.g., class as the key and student total as the
value).
• Reduce: Processes all values associated with a specific key to produce a
single result.
Map Reduce
• How it Works
• The Map Phase: The engine looks at your document. Since there are 3
students in the array, the mapFunction runs a loop and "emits" (shouts
out) three separate pairs:

• ("MCA Semester 1", {totalMarks: 251, studentCount: 1})

• ("MCA Semester 1", {totalMarks: 252, studentCount: 1})

• ("MCA Semester 1", {totalMarks: 211, studentCount: 1})


Map Reduce
• The Shuffle Phase: MongoDB collects all items with the same key
("MCA Semester 1") and puts them into an array.

• The Reduce Phase: The reduceFunction takes that array of 3


objects and adds their values together, returning one final object:
{totalMarks: 714, studentCount: 3}.
Map Reduce vs. Aggregation

Feature MapReduce Aggregation Pipeline

Language JavaScript (Slow) Native C++ (Fast)

Better for very complex JS Better for standard


Complexity
logic math/filtering

Requires a collection or
Output Returns a cursor
inline
Cursor
• A cursor is returned when find() is executed.
• Iterate Using forEach() –
• [Link]().forEach(doc => printjson(doc))
• Convert Cursor to Array
• [Link]().toArray()
• Limit Cursor Results
• [Link]().limit(2)
• Skip Dcoument
• [Link]().skip(1)
• Sort with Cursor
• [Link]().sort({ title: 1 })
Cursor Methods
• [Link]().count()
• [Link]().hasNext()
• [Link]().next()

• var cursor = [Link]();

while ([Link]()) {
printjson([Link]());
}

You might also like