Unit2 MongoDB Practical
Unit2 MongoDB Practical
com
78 74 39 11 91
www.Shyamsir.com
• Imagine a user profile system for a social media platform
where each user has different types of data:
Tables Collections
Rows
Documents(BSON)
Columns
Fields
www.Shyamsir.com
Data types
www.Shyamsir.com
Let’s open
Let’s open
www.Shyamsir.com
Let’s open
www.Shyamsir.com
Let’s open
www.Shyamsir.com
Key Concepts
www.Shyamsir.com
Key Concepts
Documents are like pages with information.
Example# Pet
{
"name": "Charlie",
"type": "Dog",
"age": 4,
"color": "Brown"
}
www.Shyamsir.com
Collection
A collection is like a whole notebook that holds many pages
(documents) about a specific topic.
www.Shyamsir.com
Schema Flexibility
In a regular school notebook, you might have to write in a
specific way or follow rules for how to organize your notes.
Example#
One page about a dog might have fields for "name" and
"age," while another page about a fish might have fields for
"name" and "water type." www.Shyamsir.com
Embedded Documents
Sometimes, you want to include extra information about
something right inside the main document. This is called
embedding.
Example#
It’s like having a contact list where you write down names
and phone numbers, but you don’t write the whole address
on every page.
www.Shyamsir.com
References
You might have a document for a dog and another for its
owner:
{
"name": "Charlie",
"owner_id": "owner_1" // This links to the owner
} Other Example of the owner data:
{
"_id": "owner_1",
"name": "Alice",
"age": 10
www.Shyamsir.com
References
Imagine you have a big box of toys, and you want to find all
the red toys.
www.Shyamsir.com
MongoDB Query Language
Most of the operations available in SQL language can be
expressend in MongoDB language.
SQL MongoDb
Select find()
www.Shyamsir.com
find and findOne
www.Shyamsir.com
Select documents
db.<collection name>.find( {<conditions>},
{<fields of interest>} );
Example#
db.emp.find();
www.Shyamsir.com
Select First document
db.<collection name>.findOne();
Example#
db.emp.findOne();
www.Shyamsir.com
find and findOne
db.emp.find()
db.emp.findOne()
www.Shyamsir.com
Select all the documents ,
with…..
db.<collection name>.find( {<conditions>}, {<fields
of interest>} );
www.Shyamsir.com
Condition and Project
SQL No SQL
{ename:1,salary:1}
www.Shyamsir.com
Only Field of Interest ,
Projection
SQL No SQL
Only Condition
SQL No SQL
www.Shyamsir.com
Order by
db.emp.find().sort({ fname: 1 })
db.emp.find().sort({ fname: -1 })
db.emp.find({},
{fname:1,lname:1,salary:1,deptname:1,_id:0}).sort({deptna
me:1}) www.Shyamsir.com
Sort
Sort is a cursor method
www.Shyamsir.com
Order by
db.emp.find({},
{ fname: 1, lname: 1, salary: 1, _id: 0 }).sort({ fname:
1 }).forEach(
doc => { print(doc.fname + "\t" + doc.lname +"\t"+
doc.salary);
});
www.Shyamsir.com
limit
www.Shyamsir.com
limit
db.emp.find().limit(3)
www.Shyamsir.com
limit
db.emp.find({},{empid:1,fname:1,salary:1,_id:0}).sort({salary:1}).limit(3)
db.emp.find({},{empid:1,fname:1,salary:1,_id:0}).sort({salary:-1}).limit(3)
db.emp.find({},{empid:1,fname:1,salary:1,_id:0}).sort({salary:-1}).limit(1)
db.emp.find({},{salary:1,_id:0}).sort({salary:-1}).limit(1)
www.Shyamsir.com
limit
db.emp.find({},{salary:1,_id:0}).sort({salary:1}).limit(1)
db.emp.find({},{fname:1,salary:1,_id:0}).sort({salary:1}).limit(1)
www.Shyamsir.com
limit
db.emp.find({}, { fname: 1, lname: 1, salary: 1, _id: 0 })
.sort({ fname: 1 })
.limit(5)
.forEach(doc => {
print(doc.fname + "\t" + doc.lname + "\t" + doc.salary);
});
www.Shyamsir.com
Query operator
www.Shyamsir.com
Query Operator
Example#
Imagine you have a collection of toys, and you want to find
all the red toys:
www.Shyamsir.com
Query Operator
Name Description
www.Shyamsir.com
Query Operator
$eq
db.emp.find({ deptname: { $eq: "IT" } })
$ne
db.emp.find({ deptname: { $ne: "IT" } })
$gt
db.emp.find({ salary: { $gt: 80000 } })
www.Shyamsir.com
Query Operator
www.Shyamsir.com
Query Operator
$gte
db.emp.find({ empid: { $gte: 22 } })
$lt
db.emp.find({ salary: { $lt: 80000 } })
$lte
db.emp.find({ empid: { $lte: 5 } })
www.Shyamsir.com
Query Operator
$in
db.emp.find({ deptname: { $in: ["HR", "Finance"] } })
db.emp.find({ empid: { $in: [1,3,5,8] } })
$nin
www.Shyamsir.com
Query Operator
$exists
db.emp.find({ gender: { $exists: true } })
$type
db.emp.find({ salary: { $type: "number" } })
www.Shyamsir.com
Query Operator
db.emp.find({ fname: { $regex: "^A", $options: "i" } })
www.Shyamsir.com
Query Operator
$regex
www.Shyamsir.com
Query Operator
Basic RegEx Search: To find users whose name starts with
"A":
db.users.find({
name: { $regex: "^A" }
});
This query will return documents where the name field starts
with "J".
www.Shyamsir.com
Query Operator
To make the search case-insensitive, you can add the i
option:
db.users.find({
name: { $regex: "^a", $options: "i" }
});
www.Shyamsir.com
Query Operator
Search for a Substring: To search for a substring "doe"
anywhere in the name field:
db.users.find({
name: { $regex: "doe", $options: "i" }
});
www.Shyamsir.com
Query Operator
$and
www.Shyamsir.com
Query Operator
$or
www.Shyamsir.com
Query Operator
$not
www.Shyamsir.com
Query Operator
Distinct – Unique values
db.emp.distinct(“deptname");
www.Shyamsir.com
Projection operator
www.Shyamsir.com
Projection Operator
Projection allows which fields are included or excluded in
your query results
Retrieve only the name and age fields for all documents.
db.students.find({}, { name: 1, age: 1 })
www.Shyamsir.com
Projection Operator
By default, MongoDB includes the _id field. To exclude it:
db.students.find({}, { _id: 0, name: 1, age: 1 })
Example# Find students with age > 20 and include only their
name.
www.Shyamsir.com
Aggregate
db.emp.aggregate([
{
$count: "totalEmployees" // Count total number of employees
}
])
db.emp.countDocuments();
www.Shyamsir.com
Aggregate
db.emp.countDocuments({salary:{$gt:90000}});
db.emp.countDocuments({deptname:"IT"});
db.emp.find({},{salary:1,_id:0}).sort({salary:-1}).limit(1)
db.emp.find({},{salary:1,_id:0}).sort({salary:1}).limit(1)
www.Shyamsir.com
Aggregate
db.emp.aggregate([
{
$facet: {maxSalary: [{ $sort: { salary: -1 } }, { $limit: 1 }, { $project: { _id: 0,
maxSalary: "$salary" } }], minSalary: [{ $sort: { salary: 1 } }, { $limit: 1 },
{ $project: { _id: 0, minSalary: "$salary" } }],
avgSalary: [{ $group: { _id: null, avgSalary: { $avg: "$salary" } } }],
totalSalary: [{ $group: { _id: null, totalSalary: { $sum: "$salary" } } }],
totalEmployees: [{ $count: "totalEmployees" }]
}
}
])
www.Shyamsir.com
Group by
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: "$deptname",
totalEmployees: { $sum: 1 }
}
}
])
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: "$gender",
totalEmployees: { $sum: 1 }
}
}
])
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: "$deptname",
maxSalary: { $max: "$salary" },
minSalary: { $min: "$salary" }
}
}
])
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: "$deptname",
avgSalary: { $avg: "$salary”}
}
}
])
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: "$deptname",
firstEmployee: { $first: "$fname" },
lastEmployee: { $last: "$fname" }
}
}
])
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: "$gender”,
totalEmployees: { $sum: 1 },
totalSalary: { $sum: "$salary" }
avgSalary: { $avg: "$salary" }
}
}
])
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: "$deptname",
totalEmployees: { $sum: 1 },
totalSalary: { $sum: "$salary" },
avgSalary: { $avg: "$salary" } }
}
])
www.Shyamsir.com
Group by
db.emp.aggregate([
{
$group: {
_id: { gender: "$gender", deptname: "$deptname" }, // Group by both
gender and department
totalEmployees: { $sum: 1 }, // Count employees in each
gender-department group
totalSalary: { $sum: "$salary" }, // Sum of salaries for each
gender-department group
avgSalary: { $avg: "$salary" } // Average salary for each
gender-department group
} } ]) www.Shyamsir.com
Views
www.Shyamsir.com
View
db.createCollection("dept_salary_view", {
viewOn: "emp",
pipeline: [
{ $group: {
_id: "$deptname",
totalSalary: { $sum: "$salary" },
totalEmployees: { $sum: 1 }
}}]
})
www.Shyamsir.com
View
db.dept_salary_view.find()
www.Shyamsir.com
Let’s create a Student
collection
www.Shyamsir.com
Collection
www.Shyamsir.com
Collection
www.Shyamsir.com
Collection
www.Shyamsir.com
InsertOne and InsertMany
www.Shyamsir.com
Open MongoDB Shell
www.Shyamsir.com
InsertMany
www.Shyamsir.com
insertOne
db.student.insertOne({
rollno: 21,
sname: "Simran",
grade: 5,
schoolname: "aone",
gender: "f",
fees: 25000
});
www.Shyamsir.com
insertOne
db.student.find({}, { _id: 0 }).forEach(
doc => {
print(doc.rollno + "\t" + doc.sname + "\t" + doc.grade +
"\t" + doc.schoolname + "\t" +
doc.gender + "\t" + doc.fees);
}
);
www.Shyamsir.com
Update Operator
www.Shyamsir.com
Update operator
db.student.updateOne(
{ rollno: 1 },
{
$set: {
fees: 20000,
schoolname: "udgam”,
grade: 4
}
}
)
www.Shyamsir.com
Update operator
db.student.findOne()
www.Shyamsir.com
Update operator
db.student.updateMany(
{ schoolname: "aone" }, // Filter condition: select all
students in "aone"
{ $inc: { fees: 5000 } } // Update operation: increment
fees by 5000
)
www.Shyamsir.com
Delete Operator
www.Shyamsir.com
Delete operator
db.students.deleteOne({ sname: "Amit" })
db.students.deleteMany({})
db.students.drop()
www.Shyamsir.com
Adding column and Updating
records
www.Shyamsir.com
Normal , findOne , check
columns
db.student.findOne();
{
_id: ObjectId('6741d1728953ffd1ba61366c'),
rollno: 1,
sname: 'Raj',
grade: 4,
schoolname: 'udgam',
gender: 'm',
fees: 20000
}
www.Shyamsir.com
Update these 2 columns for
all
db.student.updateMany(
{}, // Empty filter to match all documents
{
$set: {
maths: 0, // Default value for maths
science: 0 // Default value for science
}
}
);
www.Shyamsir.com
Let’s check record
db.student.find({}, { _id: 0 }).forEach(
doc => {
print(doc.rollno + "\t" + doc.sname + "\t" + doc.grade + "\t" +
doc.schoolname + "\t" +
doc.gender + "\t" + doc.fees + "\t" +
doc.maths + "\t" + doc.science);
}
);
www.Shyamsir.com
Let’s check record
www.Shyamsir.com
Let’s update one record
db.student.updateOne(
{ rollno: 1 }, // Filter condition: student with rollno 1
{
$set: {
maths: 85, // Set maths marks
science: 90 // Set science marks
}
}
);
www.Shyamsir.com
Let’s display one record
db.student.findOne()
www.Shyamsir.com
findOne
www.Shyamsir.com
Now fetch all the records
and toal
db.student.find({}, { _id: 0 }).forEach(
doc => {
print(doc.rollno + "\t" + doc.sname + "\t" + doc.grade + "\t" +
doc.schoolname + "\t" +
doc.gender + "\t" + doc.fees + "\t" +
doc.maths + "\t" + doc.science + "\t" + (doc.maths+doc.science));
}
);
www.Shyamsir.com
Now fetch all the records
and toal
www.Shyamsir.com
Math
www.Shyamsir.com
Math
db.sales.aggregate([
{
$project: {
total: { $add: [10, 5] }
}
}
])
www.Shyamsir.com
Math
db.numbers.aggregate([
{
$project: {
value: 1,
sqrtValue: { $sqrt: "$value" }
}
}
])
www.Shyamsir.com
Math
db.products.aggregate([
{
$project: {
product: 1,
roundedPrice: { $round: ["$price", 2] }
}
}
])
www.Shyamsir.com
Math
db.data.aggregate([
{
$project: {
value1: 1,
value2: 1,
percentage: {
$multiply: [
{ $divide: ["$value1", { $add: ["$value1", "$value2"] }] },
100
] } } } ])
www.Shyamsir.com
Math
db.products.aggregate([
{
$project: {
product: 1,
roundedPrice: { $round: ["$price", 2] }
}
}
])
www.Shyamsir.com
Math
db.numbers.aggregate([
{
$project: {
value: 1,
remainder: { $mod: ["$value", 3] }
}
}
])
www.Shyamsir.com
Array
www.Shyamsir.com
Display record ,
www.Shyamsir.com
Display record ,
{
_id: ObjectId('67469fb3fa4b0b4c6fc8f337'),
name: 'Amit Sharma',
age: 30,
skills: [
'JavaScript',
'Node.js',
'MongoDB',
'React'
],
projects: [
{
projectName: 'Website Redesign',
status: 'Completed'
},
{
projectName: 'App Development',
status: 'In Progress'
}
] www.Shyamsir.com
Display record ,
www.Shyamsir.com
Display record
db.empnewdata.find().forEach(function(employee) {
print("Name: " + employee.name);
print("Age: " + employee.age);
print("Skills: " + employee.skills.join(", "));
print("Projects:");
employee.projects.forEach(function(project) {
print(" Project Name: " + project.projectName);
print(" Status: " + project.status);
});
print("---------------");
}); www.Shyamsir.com
Count total record
db.empnewdata.countDocuments();
www.Shyamsir.com
Count how many skills are
there?
let doc = db.empnewdata.findOne({ _id:
ObjectId('67469fb3fa4b0b4c6fc8f34a') });
www.Shyamsir.com
Count how many skills are
there?
db.empnewdata.find().forEach(function(record) {
print("Name: " + record.name);
print("Number of Skills: " + record.skills.length);
print("---------------");
});
www.Shyamsir.com
Count Skills and Projects
for all
db.empnewdata.aggregate([
{
$project: {
name: 1, // Include the name for reference
skillsCount: { $size: "$skills" }, // Count the number of elements in
the skills array
projectsCount: { $size: "$projects" } // Count the number of elements
in the projects array
}
}
]);
www.Shyamsir.com
Count Skills and Projects
for all
print("Name\t\t\tSkills Count\tProjects Count");
print("-------------------------------------------------------");
db.empnewdata.find().forEach(function(record) {
let skillsCount = record.skills.length;
let projectsCount = record.projects.length;
print(record.name + "\t\t" + skillsCount + "\t\t" + projectsCount);
});
www.Shyamsir.com
Student_array
www.Shyamsir.com
Student_array
www.Shyamsir.com
Total record
db.students_array.countDocuments();
db.students_array.aggregate([
{ $group: {
_id: "$gender", // Group by the gender field
count: { $sum: 1 } // Count the number of records in each group
}
}]);
www.Shyamsir.com
Where condition
db.students_array.find({ gender: "m" }).forEach(student => {
www.Shyamsir.com
Where condition
db.students.find({
marks: {
$elemMatch: { sub: "Python", marks: { $gt: 25 } }
}
}).forEach(student => {
print(`Roll No: ${student.rollno}\tName: ${student.name}\tPython Score: $
{student.marks.find(m => m.sub === "Python").marks}`);
});
www.Shyamsir.com
Where condition
db.students_array.find({ hobbies: "Swimming" }).forEach(
student => {
print(`Name: ${student.name}
\t
Hobbies: ${student.hobbies.join(", ")}`
);
});
www.Shyamsir.com
With Total marks
db.students_array.find().forEach(student => {
const totalMarks = student.marks.reduce((sum, subject) => sum +
subject.marks, 0);
const marksDetails = student.marks.map(m => `${m.sub}: $
{m.marks}`).join(", ");
www.Shyamsir.com
Order By 1..
db.students_array.aggregate([
{
$addFields: {
totalMarks: { $sum: "$marks.marks" }
}
},
{
$sort: { totalMarks: 1 }
},
www.Shyamsir.com
Order By 1.
{
$project: {
_id: 0,
name: 1,
rollno: 1,
totalMarks: 1
}
}]).forEach(student => {
print(`Name: ${student.name}\tRoll No: ${student.rollno}\tTotal Marks: $
{student.totalMarks}`);
}); www.Shyamsir.com
Order By 1..
print("Roll No\tName\t\tMarks\t\t\t\tTotal");
print("------------------------------------------------------------");
db.students_array.find().forEach(student => {
const totalMarks = student.marks.reduce((sum, subject) => sum +
subject.marks, 0);
const marksDetails = student.marks.map(m => `${m.sub}: $
{m.marks}`).join(", ");
print(` ${student.rollno}\t${student.name}\t${marksDetails}\t$
{totalMarks}`);
});
www.Shyamsir.com
Update Record
db.students_array.updateOne(
{ rollno: 1, "marks.sub": "Python" }, // Find the record with rollno 1 and
subject "Python"
{ $set: { "marks.$.marks": 15 } } // Set Python marks to 15
);
www.Shyamsir.com
Map function
db.students_array.aggregate([
{ $project: {
name: 1,
hobbies: {
$map: {
input: "$hobbies",
as: "hobby",
in: { $concat: ["Hobby: ", "$$hobby"] }
}
} } } ]);
www.Shyamsir.com
Update Record
db.students_array.updateOne(
{ rollno: 1 }, // Find the record with rollno 1
{ $set: { "hobbies": ["Cricket", "Skating", "Chatting"] } } // Replace the
entire hobbies array
);
www.Shyamsir.com
Update Record , pop
db.students_array.updateOne(
{ rollno: 1 }, // Find student with rollno 1
{ $pop: { hobbies: 1 } } // Remove the last hobby
);
www.Shyamsir.com
Delete hobby
db.students_array.updateOne(
{ rollno: 1 }, // Find the record with rollno 1
{ $pull: { hobbies: "Cricket" } } // Remove "Cricket" from the hobbies array
);
www.Shyamsir.com
Push hobby
db.students_array.updateOne(
{ rollno: 1 }, // Find the record with rollno 1
{ $push: { hobbies: "Swimming" } } // Add "Swimming" to the hobbies
array
);
www.Shyamsir.com
Unset column
db.students_array.updateOne(
{ rollno: 1 }, // Find the record with rollno 1
{ $unset: { hobbies: "" } } // Remove the hobbies array field
);
www.Shyamsir.com
Display heights marks…1
db.students_array.aggregate([
{
$addFields: {
totalMarks: { $sum: "$marks.marks" }
}
},
{
$sort: { totalMarks: -1 }
},
{
$limit: 1 www.Shyamsir.com
Display heights marks…1
},
{
$project: {
_id: 0,
rollno: 1,
name: 1,
totalMarks: 1
}
}
www.Shyamsir.com
Display heights marks…1
]).forEach(student => {
print(`Roll No: ${student.rollno}\tName: ${student.name}\tTotal Marks: $
{student.totalMarks}`);
});
www.Shyamsir.com
Display first 2 hobbies
db.students_array.aggregate([
{ $project: {
name: 1,
hobbies: { $slice: ["$hobbies", 2] } // Limit hobbies array to the first 2
elements
}
}
]);
www.Shyamsir.com