0% found this document useful (0 votes)
41 views

Unit2 MongoDB Practical

The document outlines a user profile system for a social media platform, detailing various user data structures and product information. It also compares SQL and MongoDB databases, explaining key concepts such as documents, collections, schema flexibility, embedded documents, and references. Additionally, the document covers MongoDB query language, operators, and projection techniques for data retrieval.

Uploaded by

Zain Ayaan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Unit2 MongoDB Practical

The document outlines a user profile system for a social media platform, detailing various user data structures and product information. It also compares SQL and MongoDB databases, explaining key concepts such as documents, collections, schema flexibility, embedded documents, and references. Additionally, the document covers MongoDB query language, operators, and projection techniques for data retrieval.

Uploaded by

Zain Ayaan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 148

www.Shyamsir.

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:

• User A has: { name: "Alice", hobbies: ["painting", "traveling"] }

• const userH = { name: "Harsha", age: 29, profession: "Teacher" };

• const userI = { name: "Ishaan", age: 32, profession: "Software


Developer" };

• const userJ = { name: "Jhanvi", age: 27, profession: "Graphic


Designer" };

• const userK = { name: "Karthik", age: 35, profession: "Data


Scientist" };
www.Shyamsir.com
Product: Laptop Product: Furniture
{ {
"name": "Gaming "name": "Office Chair",
Laptop", "brand": "ABC",
"brand": "XYZ", "price": 200,
"price": 1500, "material": "Leather",
"specifications": { "dimensions": {
"processor": "Intel i7",
"height": "42 inches",
"RAM": "16GB",
"width": "24 inches"
"storage": "512GB
SSD" },
}, "assemblyRequired":
true
"warranty": "1 year"
}
} www.Shyamsir.com
MySQL vs MongoDB
SQL MongoDB
Database Database

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.

Collections are like notebooks that hold many pages.

Schema Flexibility means you can organize your information


however you want.

Embedded Documents let you add extra details right inside a


document.

References allow you to link documents together without


repeating information.
www.Shyamsir.com
Document
Think of a document as a single page in a notebook contains
,piece of information about something, and it looks like a list
of facts written in a special way called JSON.

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.

In MongoDB, documents that are similar are grouped


together in a collection.

Example: You might have a collection called "Pets" that


contains all the documents for each of your pets:

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.

But in MongoDB, you can write your documents however you


want! This is
called schema flexibility.

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.

It’s like adding sticky notes to a page to give more details.

Example#

If you have a document about a dog that also includes a list


of its toys, it might look likewww.Shyamsir.com
this:
Embedded Documents
{
"name": "Charlie",
"type": "Dog",
"toys": [
{
"name": "Ball",
"color": "Red"
}
}
www.Shyamsir.com
References
Instead of putting all the information in one document,
sometimes it’s better to keep things separate and link them
together. This is called referencing.

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.

A query operator helps you ask the right question to find


those red toys in the box.

In MongoDB, a query operator helps you search for specific


data in a database.

www.Shyamsir.com
MongoDB Query Language
Most of the operations available in SQL language can be
expressend in MongoDB language.

SQL MongoDb
Select find()

Select * from emp db.emp.find()

www.Shyamsir.com
find and findOne

www.Shyamsir.com
Select documents
db.<collection name>.find( {<conditions>},
{<fields of interest>} );

Example#
db.emp.find();

Returns all documents contained in the emp collection

www.Shyamsir.com
Select First document
db.<collection name>.findOne();

Example#
db.emp.findOne();

Returns only first document contained in the emp collection

www.Shyamsir.com
find and findOne
db.emp.find()

db.emp.findOne()

db.emp.findOne({}, { fname: 1, lname: 1})

db.emp.findOne({}, { fname: 1, lname: 1, _id: 0 })

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

Select ename,salary db.emp.find


from emp (
where salary>25000
{salary:{$gt:25000}},

{ename:1,salary:1}

www.Shyamsir.com
Only Field of Interest ,
Projection
SQL No SQL

Select ename,salary from emp db.emp.find(


{},
{ename:1,salary:1}
)

Only Condition
SQL No SQL

Select * from emp db.emp.find(


where salary>20000 {salary:{$gt:20000}},
{}
)
www.Shyamsir.com
Ascending / Descending

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, _id:


0 }).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

sort( {<list of field:value pairs>} ); Field specifies which filed


is used to sort the returned documents

value = -1 descending order


Value = 1 ascending orde

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);
});

db.emp.find({}, { fname: 1, lname: 1, salary: 1, _id:


0 }).sort({salary : 1 }).forEach(doc => {
print(doc.fname + "\t" + www.Shyamsir.com
doc.lname +"\t"+ doc.salary);
Order by

db.emp.find({}, { fname: 1, lname: 1, salary: 1, deptname:


1, _id: 0 })
.sort({ deptname: 1, fname: -1 })

www.Shyamsir.com
limit

www.Shyamsir.com
limit
db.emp.find().limit(3)

db.emp.find({ deptname: “Sales" }).limit(2)

db.emp.find().sort({ fname: -1 }).limit(5)

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:

db.toys.find({ color: "red" });

www.Shyamsir.com
Query Operator
Name Description

$eq : Matches values that are equal to a specified value


$gt : Matches values that are greater than a specified value
$gte: Matches values that are greater than or equal to a specified value
$in : Matches any of the values specified in an array
$lt : Matches values that are less than a specified value
$lte : Matches values that are less than or equal to a specified value
$ne : Matches all values that are not equal to a specified value
$nin : Matches none of the values specified in an array

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

db.emp.find({ empid: { $gte: 22 } })


.forEach(doc => {
print( doc.empid + "\t" + doc.fname + "\t" + doc.lname
+ "\t" + doc.salary +"\t" + doc.deptname +"\t"+ doc.gender
+"\t"+ doc.city );
});

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

db.emp.find({ deptname: { $ne: "IT" } })


db.emp.find({ empid: { $nin: [1,3,5,8] } })

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" } })

db.emp.find({ fname: { $regex: "a", $options: "i" } })

db.emp.find({ fname: { $regex: "a$", $options: "i" } })

db.emp.find({ fname: { $regex: "^.a", $options: "i" } })

www.Shyamsir.com
Query Operator
$regex

Regular expressions in queries to search for patterns within


string data stored in the database. MongoDB supports
regular expression searches via the $regex operator, which
allows you to find documents where a specified field
matches a regular expression pattern.

db.emp.find({ fname: { $regex: "^A" } })

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" }
});

This would match names like "John", "jane", "JAMES", etc.

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" }
});

This query would match any name containing "doe", like


"Doe", "doe", or "John Doe".
www.Shyamsir.com
Query Operator
db.emp.find({ fname: { $regex: "^..a", $options: "i" } })

db.emp.find({ fname: { $regex: "a.$", $options: "i" } })

db.emp.find({ fname: { $regex: "^[AEIOUaeiou]" } },


{ fname: 1, _id: 0 });

db.emp.find({ fname: { $regex: "^[^AEIOUaeiou]" } },


{ fname: 1, _id: 0 });
www.Shyamsir.com
Query Operator
Operator Meaning
$and All the condition
$or At least One
$not Other than this

www.Shyamsir.com
Query Operator
$and

db.emp.find({ $and: [ { deptname: "Sales" }, { salary: { $gt:


40000 } } ] })

db.emp.find({ $and: [ { salary: { $gt: 30000 } }, { salary:


{ $lt: 40000 } } ] })

www.Shyamsir.com
Query Operator
$or

db.emp.find({ $or: [ { deptname: "HR" }, { salary: { $lt:


30000 } } ] })

db.emp.find({ $or: [ { fname: { $regex: "^A" } }, { fname: {


$regex: "^V" } } ] })

www.Shyamsir.com
Query Operator
$not

db.emp.find({ city: { $not: { $regex: "^B" } } })

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 })

Exclude the address field from the results


db.students.find({}, { address: 0 })

www.Shyamsir.com
Projection Operator
By default, MongoDB includes the _id field. To exclude it:
db.students.find({}, { _id: 0, name: 1, age: 1 })

Combine projections with query conditions to refine results.

Example# Find students with age > 20 and include only their
name.

db.students.find({ age: { $gt: 20 } }, { name: 1, _id: 0 })


www.Shyamsir.com
Aggregation

www.Shyamsir.com
Aggregate
db.emp.aggregate([
{
$count: "totalEmployees" // Count total number of employees
}
])

db.emp.countDocuments();

db.emp.countDocuments({ gender: "m" });

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({ fees: { $gt: 20000 } })

db.students.deleteMany({ $expr: { $lt: [{ $add: ["$maths", "$sci", "$eng"] },


50] } });

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') });

let skillsCount = doc.skills.length;

print("Total skills:", skillsCount);

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.countDocuments({ gender: "m" });

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 => {

print(`Roll No: ${student.rollno}\tName: ${student.name}


\tHobbies:
${student.hobbies.join(", ")}
\tMarks:
${student.marks.map(m => `${m.sub}: ${m.marks}`).join(", ")}`);
});

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(", ");

print(`Roll No: ${student.rollno}\tName: ${student.name}\tMarks: $


{marksDetails}\tTotal: ${totalMarks}`);
});

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

You might also like