【问题标题】:Mongodb aggregate query with not inmongodb 聚合查询不包含在
【发布时间】:2014-11-24 21:09:48
【问题描述】:

我在一个集合中有学生列表,在另一个集合中有他们的成绩。架构(去除其他细节)看起来像

学生

{
     _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" } }

我觉得因为返回值是两个深匹配不起作用。得到这个的正确方法是什么?

【问题讨论】:

  • db.students.find({}, {_id: 0, 'student.code': 1}) 不会为您提供学生代码数组。它为您提供包含字段 studentCodes 的文档数组。所以 $nin 无法识别它。

标签: mongodb aggregation-framework


【解决方案1】:

使用此代码

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

【讨论】:

  • @mallik,$nin 运算符使用数组格式。以下列格式更新您的答案。 { $nin: [ 'value1', 'value2' ]}
  • 如果你使用 _id in 或不 in ,请使用 this => ids = ids.map(function(el) { return mongoose.Types.ObjectId(el) })
猜你喜欢
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多