使用从一个模型填充到另一个模型检索数组数据

Retrieve Array Data Using Populate from One Model to Another

这是我的 MongoDB 数据库的两个模型。

QuestionsInfo


{
    "_id": ObjectId("60e5f5fce2446faa95e6eca7"),
    "courseName": "ML",
    "user": ObjectId("6087dc4c2ba7a828363c9fca"),
    "questions": [
        {
            "questionInput": {
                "question": "This is the first Question. `(a+b)^2` ",
            },
            "id": "aLC/QNz/AOLO9Fyj7oJT",
            "createdAt": "2021-07-07T18:41:18.971Z"
        },
        {
            "questionInput": {
                "question": "This is the first Question. `(a+b)^2` ",
            },
            "id": "aLC/QNz/AOLO9Fyj7oJJ",
            "createdAt": "2021-07-07T18:41:19.971Z"
        },
        {
            "questionInput": {
                "question": "This is the third Question.ΒΓ",
            },
            "id": "qPgd261wVGizOuR1b9RT",
            "createdAt": "2021-07-07T18:46:25.203Z"
        }
    ]
}

ExamInfo

questionsInfoQuestionsInfo模型的id。这是由 MongoDB 引用创建的。

{
    "_id": ObjectId("60e5f88159292f575c0ca17f"),
    "questionsId": [
        "aLC/QNz/AOLO9Fyj7oJT",
        "aLC/QNz/AOLO9Fyj7oJJ"
    ],
    "user": ObjectId("6087dc4c2ba7a828363c9fca"),
    "questionsInfo": ObjectId("60e5f5fce2446faa95e6eca7"),
}

我想使用填充到 ExamInfo 模型中从 QuestionsInfo 中查找与 questionsId 列表匹配的问题。

我该怎么做?提前致谢。

以下是实现此目标的方法。

{
    $lookup: {
      from: "questionsInfo",
      let: {
        qId: "$questionsInfo",
        internalQIds: "$questionsId"
      },
      as: "questionsInfo",
      pipeline: [
        // first match question info document
        {
          $match: {
            $expr: {
              $eq: [
                "$_id",
                "$$qId"
              ]
            }
          }
        },
        // unwind all nested questions
        {
          $unwind: "$questions"
        },
        // match only required questions
        {
          $match: {
            $expr: {
              $in: [
                "$questions.id",
                "$$internalQIds"
              ]
            }
          }
        },
        // regroup
        {$group: {
          _id: "$_id",
          courseName: {
            $first: "$courseName"
          },
          user: {
            $first: "user"
          },
          questions: {
            $push: "$questions"
          }
        }
      },
      
    ]
  }
}

现在,由于查找 returns 数组,您可以使用类似这样的方法从数组中取出问题信息。

{
  "$addFields": {
    "questionsInfo": {
      "$arrayElemAt": [
        "$questionsInfo",
        0
      ]
    }
  }
}

https://mongoplayground.net/p/lYQAUFyEUMr