将 id 存储在 mongodb 中的对象数组中的两个集合连接起来

问题描述

我有两个名为 SchoolStudents

的集合

学校收藏

   {
      _id: ObjectId("60008e81d186a82fdc4ff2b7"),name: String,branch: String,class: [{
             "active" : true,"_id" : ObjectId("6001e6871d985e477b61b43f"),"name" : "I","order" : 1
        },{
             "active" : true,"_id" : ObjectId("6001e68f1d985e477b61b444"),"name" : "II","order" : 2
        }]
   }

学生合集

  {
      _id: ObjectId("6002def815eccd53a596f830"),schoolId: ObjectId("60008e81d186a82fdc4ff2b7"),sessionId: ObjectId("60008e81d186a82fdc4ff2b9"),class: ObjectId("6001e6871d985e477b61b43f"),}

我想在单次查询中获取Student Collection的数据。

我将类 id 存储在学生集合中,而针对该 id 的数据存储在类键下的学校集合中,该类是对象数组。

你能帮我用这个 id 获取学生集合中的类对象吗?

我想要的输出:

data: {
  _id: ObjectId("6002def815eccd53a596f830"),classData: [{
        "active" : true,"order" : 1
    }]

}

所以我尝试了这个,但没有用:

const students = await this.studentModel.aggregate([
{
  $lookup: {
    from: 'School',let: { classId: '$class' },pipeline: [
      {
        $match: {
          $expr: { $eq: ['$$classId','$class._id'] },},],as: 'classData',]);

解决方法

  • $lookup,在schoolId中传递classlet
  • $match 学校 id 条件
  • $filter 迭代 class 的循环并过滤特定的类对象
  • $arrayElemAt 将从 $filter 的返回结果中获取对象
  • $replaceRoot 将对象替换为 root
const students = await this.studentModel.aggregate([
  {
    $lookup: {
      from: "School",let: {
        schoolId: "$schoolId",classId: "$class"
      },pipeline: [
        { $match: { $expr: { $eq: ["$$schoolId","$_id"] } } },{
          $replaceRoot: {
            newRoot: {
              $arrayElemAt: [
                {
                  $filter: {
                    input: "$class",cond: { $eq: ["$$this._id","$$classId"] }
                  }
                },0
              ]
            }
          }
        }
      ],as: "classData"
    }
  }
])

Playground

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...