Database

db={"collection":[{"_id":"635d40803352895afffdc294","name":"D R","email":"dugu@gmail.com","number":"9198998888","rollNumber":202,"departmentID":"635a8ca21444a47d65d32c1a","classID":"635a92141a081229013255b4","position":"Student",},{"_id":"635eb8898dea5f437789b751","name":"V R","email":"v@gmail.com","number":"9198998899","rollNumber":203,"departmentID":"635a8ca21444a47d65d32c1a","classID":"635a92141a081229013255b4","position":"Student",}],"attendances":[{subjectID:2,"studentID":"635d40803352895afffdc294"},{subjectID:2,"studentID":"635eb8898dea5f437789b751"},{subjectID:2,"studentID":"635d40803352895afffdc294"},{subjectID:2,"studentID":"635eb8898dea5f437789b751"},{subjectID:2,"studentID":"635d40803352895afffdc294"},]}

Query

db.collection.aggregate([{$match:{classID:"635a92141a081229013255b4"}},{$project:{createdAt:0,updatedAt:0,__v:0,password:0}},{$lookup:{from:"attendances",let:{studentID:"$_id"},pipeline:[{$match:{subjectID:2,$expr:{$eq:["$$studentID","$studentID"]}}},{$unwind:"$studentID"},{$group:{_id:"$studentID",count:{$sum:1}}}],as:"present",},},])

Result