我正在学习使用mongodb。我做了3个集合(用户,注册,课程)
User
+--------------------------------------+---------+--------+
| _id | user_id | name |
+--------------------------------------+---------+--------+
| ObjectId("5ee6c0511d0843811413b225") | 1 | John |
+--------------------------------------+---------+--------+
| ObjectId("5ef9e9b11db598099e183319") | 2 | Bob |
+--------------------------------------+---------+--------+
Courses
+--------------------------------------+---------+-----------------+
| _id | courseID| courseName |
+--------------------------------------+---------+-----------------+
| ObjectId("5ef9d1b28e08e1c04ac9530b") | "1111" | English |
+--------------------------------------+---------+-----------------+
| ObjectId("5ef9db2bdd883a3444dd396a") | "2222" | Algebra 1 |
+--------------------------------------+---------+-----------------+
| ObjectId("5ef9ea212c72182edf809a52") | "3333" | World History |
+--------------------------------------+---------+-----------------+
| ObjectId("5ee6c0511d0843811413b226") | "4444" | Algebra 2 |
+--------------------------------------+---------+-----------------+
Enrollment
+---------+----------+
| user_id | courseID |
+---------+----------+
| 1 | "1111" |
+---------+----------+
| 2 | "2222" |
+---------+----------+
| 1 | "2222" |
+---------+----------+
| 1 | "4444" |
+---------+----------+每次用户单击某个课程时,都会将其添加到注册表中。我可以为用户显示注册名单,但我不知道如何显示未被用户注册的课程。
我想知道如何显示未按用户添加到注册表中的课程?我试着使用user_id: { $ne: 1 },但是似乎没有显示出没有被注册的正确的课程。
如何正确显示?
发布于 2020-06-30 04:28:42
您可以使用聚合
假设你了解user_id,假设我们选择了user_id: 2的鲍勃
您可以先从Course获取所有课程,然后只筛选用户尚未注册的课程。
db.Course.aggregate({
$lookup: { // "join" with Enrollment
from: "Enrollment",
localField: "courseID",
foreignField: "courseID",
as: "enrollments"
},
},
{
$match: { // only match courses that user_id 2 doesn't exist in list of enrolments
"enrollments.user_id": {
$ne: 2
}
}
})或者从特定的Enrollment开始,从Course找到课程
db.Enrollment.aggregate({
$match: { // find enrolments of user_id 2
user_id: 2
}
},
{
$group: { // combine all courseID into an array
_id: "$user_id",
courseIDs: {
$push: "$courseID"
}
}
},
{
$lookup: { // "join" with Course that is not in the list of enrolments
from: "Course",
as: "notEnrolledCourses",
let: {
courseIDs: "$courseIDs"
},
pipeline: [
{
$match: {
$expr: {
$not: {
$in: [
"$courseID",
"$$courseIDs"
]
}
}
}
}
]
}
})请注意,上述方法没有相同的输出结构,您将不得不操作以获得所需的输出形状。
发布于 2020-06-30 04:11:41
有了这个收藏结构:
步骤1:获取用户的注册课程列表。例如:用户2的课程:2222
步骤2:使用Courses集合上的find查询({ courseID: { $nin: ['2222'] } })获取未注册的课程列表.
但是,我建议您通过以下任何一种方式更新集合的模式:
User集合中。Enrollment集合中的数组中。这样,您就可以在步骤1中消除某些处理。
希望这能有所帮助!
https://stackoverflow.com/questions/62649133
复制相似问题