我在一个集合中有学生列表,在另一个集合中有他们的成绩。架构(去除其他细节)看起来像
学生
{
_id: 1234,
student: {
code: "WUKD984KUK"
}
}
成绩
{
_id: 3456,
grade: 24,
studentCode: "WUKD984KUK"
}
每个学生可以有多个成绩条目。我需要在成绩表中但不在学生表中的学生总数。我还需要为每个不在学生表中的学生计算成绩。以下是我写的查询,
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'}}}
);
但这会返回我所有的学生详细信息,就好像匹配不起作用一样。当我只运行此查询的第一部分时,我将学生详细信息作为
{ "student" : { "code" : "A210225504104" } }
我觉得因为返回值是两个深匹配不起作用。得到这个的正确方法是什么?
最佳答案
使用此代码
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'}}}
);
关于mongodb 聚合查询不包含在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26117447/