mongodb按外键对象计数d

xdnvmnnf  于 2023-03-01  发布在  Go
关注(0)|答案(1)|浏览(83)

获取章节代码

getChapters: async (parent, args) => {
    const chapters = await Chapter.find({});
    for (let chapter of chapters) {
      const questions = await Question.countDocuments({
        subjectRef: args.subjectRef,
        chapterRef: chapter._id,
      });
      chapter.count = questions;
    }
    return chapters;
  }

章节数据

{
      _id: ObjectId("630690f0c8099a159e73783f"),
      chapter_name: 'حرف الدال',
      subjectRef: ObjectId("630690f0c8099a159e73781b"),
      createdAt: ISODate("2022-08-24T20:58:24.659Z"),
      updatedAt: ISODate("2022-08-24T20:58:24.659Z"),
      __v: 0
    }

问题数据

{
      _id: ObjectId("630680a764a8eb1364c4f276"),
      question_type: 'MULTIPLE CHOICE',
      published: true,
      status: 'PUBLISHED',
      question_info: '<p>Fill in the blanks with the correct option:&nbsp;</p>\n' +
        '<p>My mother is a teacher. She __________ math.</p>',
      option_1: 'takes',
      option_2: 'take',
      option_3: 'teaches',
      option_4: 'teach',
      answer: '3',
      subjectRef: ObjectId("63064f22dc0bc90b0e32c620"),
      gradeRef: ObjectId("63064f21dc0bc90b0e32c581"),
      chapterRef: ObjectId("63064f22dc0bc90b0e32c632"),
      levelRef: ObjectId("63067b8cb36f1c0c73f01da8"),
      teacherRef: ObjectId("63066f7bcac6d3c599c8cb7a"),
      createdAt: ISODate("2022-08-24T19:48:55.949Z"),
      updatedAt: ISODate("2022-08-24T19:48:55.949Z"),
      __v: 0,
      curriculumRef: ObjectId("630690f0c8099a159e7377dc")
  }

结果

[
    {
      "chapter_name": "حرف الذال",
      "id": "630690f0c8099a159e73781e",
      "count": 29
    },
    {
      "chapter_name": "انشطة القصة المشتركة احلام عالية",
      "id": "630690f0c8099a159e737821",
      "count": 11
    }
  ]

我得到了这个结果。这个结果是正确的,但它没有优化,因为它在每个查询中循环,并得到计数。我想优化查询,以便它将计数这个。请检查我如何解决这个问题

uidvcgyl

uidvcgyl1#

您可以使用聚合管道,如下所示:

db.chapters.aggregate([
  {
    "$lookup": {
      "from": "questions",
      "let": {
        id: "$_id"
      },
      "pipeline": [
        {
          "$match": {
            "$and": [
              {
                subjectRef: ObjectId("630690f0c8099a159e73781b")
              },
              {
                $expr: {
                  "$eq": [
                    "$$id",
                    "$chapterRef"
                  ]
                }
              }
            ]
          }
        },
        
      ],
      "as": "questions"
    }
  },
  {
    "$project": {
      chapter_name: 1,
      count: {
        "$size": "$questions"
      },
      id: "$_id",
      _id: 0
    }
  }
])

在这个查询中,我们首先使用$lookup查找一个章节中特定主题的问题,然后计算每个章节的问题数。
Playground link.

相关问题