繁体   English   中英

在mongodb中使用$ lookup指定多个联接条件

[英]Specify Multiple Join Conditions with $lookup in mongodb

我有这两个集合,我想作为2个条件加入:examId和用户ID。我使用的是mongodb版本4和nodejs。我的应用程序考试中没有猫鼬:

{"_id" : ObjectId("5c4c21d8f45b3d53ff8c20a3"),
  "title" : "first azmoon",
  "time" : 600,
  "preLesson" : {
   "label" : "Lesson 13",
   "value" : ObjectId("5c484e1852faa438c36c3da1")
},
}

结果: { "_id" : ObjectId("5c4993d5d0dc6f39c0f324bd"), "usrId" : ObjectId("5c484e8852faa438c36c3da2"), "lsnId" : ObjectId("5c484e1852faa438c36c3da1"), "passedLesson" : false, "timePassed" : "", "quiz" : { "time" : "5", "questionTrue" : 0, "getScore" : 0, "permission" : true, "quizScore" : 15, "quizCount" : 3 }, "exam" : { "examScore" : 0, "examCount" : 0, "getScore" : 0, "time" : 600, "questionTrue" : 0, "permission" : false, "exId" : ObjectId("5c4c21d8f45b3d53ff8c20a3") } }

我想要其psodou SQL代码如下的结果:

select * from exams left join result on exam._id = result.exam.exaId 
     where result.usrId =  ObjectId("5c484e8852faa438c36c3da2")

我已经完成了以下工作,但没有任何条件就只能参加考试和成绩

   con.collection("exam").aggregate([
            {
                $lookup: {
                    from: "result",
                    let: {exaId: "$_id"},
                    pipeline: [
                        {
                            $match: {
                                $expr: {
                                    $and: [
                                         {$eq: ["exam.exId", "exaId"]},
                                        {"usrId": new 
                                       ObjectID(`${usrId}`)}
                                    ]
                                }
                            }
                        },
                    ],
                    as: "result"
                }
            },
            {
                $lookup: {
                    from: "lesson",
                    localField: "preLesson.value",
                    foreignField: "_id",
                    as: "lesson"
                },

            }
        ])

我不知道这是什么问题,如果有人可以帮助我,我将不胜感激。

您错过$ $eq运算符中的$符号

con.collection("exam").aggregate([
  { "$lookup": {
    "from": "result",
    "let": { "exaId": "$_id" },
    "pipeline": [
      { "$match": {
        "$expr": { "$eq": ["$exam.exId", "$$exaId"] },
        "usrId": mongoose.Types.ObjectID(`${usrId}`)
      }}
    ],
    "as": "result"
  }},
  { "$lookup": {
    "from": "lesson",
    "localField": "preLesson.value",
    "foreignField": "_id",
    "as": "lesson"
  }}
])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM