MongoDb 管道聚合以获取子子文档返回相同的数字

问题描述 投票:0回答:0

我有学校、班级和学生模型和模式。

School(_id,stx, location, classes?)
Class(_id, level, classesCount)
Student(_id,age,boyz,girls)
.

这是我按 stx、位置和级别分组的管道。

const pipeline = SchoolModel.aggregate([
  {
    $match: {year: '2021-2022'}
  },
  {
    $unwind: "$classes"
  },
  {
    $unwind: "$classes.students"
  },
  {
    $group: {
      _id: {
        stx: "$stx",
        location: "$location",
        level: "$classes.level"
      },
      boyz: {
        $sum: "$classes.students.boyz"
      },
      girls: {
        $sum: "$classes.students.girls"
      }
    }
  },
  {
    $project: {
      _id: 0,
      stx: "$_id.stx",
      location: "$_id.location",
      level: "$_id.level",
      boyz: 1,
      girls: 1,
    }
  }
]);

const results = await pipeline.exec();

res.status(200).json(results);

为什么这个管道在结果中错误地返回相同的女孩和男孩计数?如何展开和/分组以获得正确的结果?

mongodb aggregation-framework pipeline mongoose-schema
© www.soinside.com 2019 - 2024. All rights reserved.