我有两个要作为两个条件加入的集合.exemId和用户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"
},
}
])
我不知道问题出在什么地方,如果有人可以帮助我,我将不胜感激。
答案 0 :(得分:2)
您错过了$
运算符内的$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"
}}
])