[英]MongoDB - not in other table (many-to-many relationship)
我正在學習使用 mongodb。 我做了 3 collections(用戶,注冊,課程)
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 }
,但似乎沒有顯示尚未注冊的正確課程。
如何正確顯示?
您可以使用聚合
假設您知道user_id
,假設我們選擇 Bob 的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
}
}
})
或者從特定User
的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"
]
}
}
}
}
]
}
})
請注意,上述方法不具有相同的 output 結構,您將不得不操作以獲得所需的 output 形狀。
使用此集合結構:
第 1 步:獲取用戶的已注冊課程列表。 例如:用戶 2 的課程:['2222']
第 2 步:在Courses
集合上使用find
查詢 ( { courseID: { $nin: ['2222'] } }
) 來獲取未注冊的課程列表。
但是,我建議您通過以下任一方式更新集合的架構:
User
集合中的已注冊課程 ID 保存在一個數組中。Enrollment
集合中的數組中。這樣,您可以消除步驟 1 中的一些處理。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.