Mongodb summary query with

I have a list of students in one collection and their grades in another collection. The circuit (devoid of other details) looks like

Students

{ _id: 1234, student: { code: "WUKD984KUK" } } 

Classes

 { _id: 3456, grade: 24, studentCode: "WUKD984KUK" } 

For each student, there may be several entries. I need the total number of students who are in the class table, but not in the student table. I also need the number of grades for each student that are not in the student table. Below is the query I wrote,

 var existingStudents = db.students.find({}, {_id: 0, 'student.code': 1}); db.grades.aggregate( {$match: { 'studentCode': {'$nin': existingStudents}}}, {$group: {_id: '$studentCode', count:{$sum: 1}}}, {$project: {tmp: {code: '$_id', count: '$count'}}}, {$group: {_id: null, total:{$sum:1}, data:{$addToSet: '$tmp'}}} ); 

But this gives me all the student details, as if the match wasn’t working. When I run only the first part of this query, I get student information as

 { "student" : { "code" : "A210225504104" } } 

I feel that since the return value is two, the match does not work. What is the right way to get this?

+5
source share
1 answer

Use this code

 var existingStudents=[]; db.students.find({}, {_id: 0, 'student.code': 1}).forEach(function(doc){existingStudents.push(doc.student.code)}) db.grades.aggregate( {$match: { 'studentCode': {'$nin': existingStudents}}}, {$group: {_id: '$studentCode', count:{$sum: 1}}}, {$project: {tmp: {code: '$_id', count: '$count'}}}, {$group: {_id: null, total:{$sum:1}, data:{$addToSet: '$tmp'}}} ); 
+8
source

Source: https://habr.com/ru/post/1203694/


All Articles