Skip to content
js
;(async () => {
  // 聚合查询
  const res = await HomeWork
    .aggregate([
      {
        $lookup: {
          from: 'student', // 查询哪个表
          localField: 'studentId', // 保存在作业表中的哪个字段
          foreignField: '_id', // 关联的学生表中的 _id 字段
          as: 'user' // 别名
        }
      },
      {
        // 查询数量
        $limit: 2
      },
      {
        // 查询结果只显示的字段
        $project: {
          title: 1
        }
      },
      {
        // 分组
        $group: {
          _id: '$name',
          // age: { $avg: "$age" }
        }
      },
      {
        $match: {
          _id: mongoose.Types.ObjectId('6301d1bda05f4b3b5339a883')
        }
      }
    ])
    console.log(res[0])
})()