Wednesday, January 27, 2021

MongoDB Aggregation

Student Collection:  Download Student.json

// Function to Count no. of Documents in a Collection
db.student.count()


db.student.aggregate([
    //stage-1
    {$match: {sec:"B"} },
    //stage-2 
    {$count: "Total-Student in Sec:B"}
])

db.student.aggregate([
    //stage-1
     {$match: {sec:"B"} },
     //stage-2
     {$group: {_id:"$gender", total_st: {$sum:1}, max_age:{$max:"$age"} } },
     //stage-3
     {$match: {_id:"male"}},
       //stage-4
     {$project: {"max_age":1}}
 ])


 db.student.aggregate([
     //stage-1
     {$group:{_id:"$sec", total_stu:{$sum:1}}},
     //stage-2
     {$sort: {_id:1}},
     //stage-3
     {$skip:1},
     //stage-4
     {$limit:2},
     //stage-5
     {$out: "FilteredCollection"}
 ])


// -------------------Example------------------------
db.skill.insert([
    {name:"pankaj", skills:["c","c++", "python", "java", "web"]},
    {name:"sachin", skills:["web", "python", "java"]},
    {name:"manish", skills:["ml", "Iot", "web"]}
])

Problem: Find the name of the students who are having "web" as their skills.

db.skill.find({skills:"web"})

// Using Aggregation

db.skill.aggregate([
    {$group:"$skills"}
])

// ----
// $unwind stage
// ----

db.skill.aggregate([
    {$unwind:"$skills"}
])

// ----
// $unwind and group stage
// ----

db.skill.aggregate([
    {$unwind:"$skills"}
    {$group:{_id:"$skills"}}
])

// --------Solution to the Problem ------------------------

db.skill.aggregate([
    {$unwind:"$skills"},
    {$group:{_id:"$skills",count:{$sum:1}, names:{$push:"$name"}}}
    {$match:{_id:"web"}}
])