我有一個名為“CourseCollection”的 mongo 集合,它包含父檔案和子檔案。任何帶有“父”鍵的檔案都是子檔案,并且父檔案可以有多個子檔案。
{
"_id" : "abracadavra",
"Name" : "abracadavra",
"Description" : "",
"Type" : "Spell",
"Parent" : {
"_id" : "Magic",
"Type" : "Course",
"Name" : "Magic"
}
},
{
"_id" : "Magic",
"Name" : "Magic",
"Type" : "Course",
"Access" : [
{
"_id" : "2sssdw5oe",
"Name" : "Abc"
},
{
"_id" : "4fddfye42",
"Name" : "Xyz"
}
]
}
我想要做的是,基于父檔案的訪問,我正在嘗試獲取所有子檔案。
現有和有效的解決方案:
我目前的解決方案是執行 2 個查詢。
查詢 1. 獲取用戶可以訪問的所有課程。
db.getCollection("CourseCollection").find({"Type": "Course", "Access._id": {"$in": ["2sssdw5oe"]}})
查詢 2。由于我使用的是 Python,因此我執行串列推導以僅獲取課程的 ID,然后使用此串列執行另一個查詢
db.getCollection("CourseCollection").find({"Type": "Spell", "Parent._id": {"$in": course_list_id}})
有沒有辦法在單個查詢中過濾掉父級后獲取子級資料。我也嘗試過聚合,但只有前一階段的結果會傳遞到下一階段。
uj5u.com熱心網友回復:
我猜你正在嘗試做這樣的事情:
db.CourseCollection.aggregate([
{
"$match": {
"Type": "Spell"
}
},
{
"$lookup": {
"from": "CourseCollection",
"localField": "Parent._id",
"foreignField": "_id",
"as": "Parents"
}
},
{
"$match": {
"Parents": {
"$elemMatch": {
"Type": "Course",
"Access._id": {
"$in": [
"2sssdw5oe"
]
}
}
}
}
}
])
這樣做也可以達到相同的結果:
db.CourseCollection.aggregate([
{
"$match": {
"Type": "Spell"
}
},
{
"$lookup": {
"from": "CourseCollection",
"localField": "Parent._id",
"foreignField": "_id",
"as": "Parents",
"pipeline": [
{
"$match": {
"Type": "Course",
"Access._id": {
"$in": [
"2sssdw5oe"
]
}
}
}
]
}
},
{
"$match": {
"Parents.0": {
"$exists": true
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431855.html
