我有一個 mongo db 集合,其中每個檔案都有兩個嵌套陣列(每個檔案都有一個元素存盤一個陣列,該陣列存盤存盤另一個陣列的檔案),我只想要最深檔案的一些欄位。我嘗試了不同型別的投影元素,但都沒有奏效。現在我正在嘗試以下操作:
let answered_exam = await exams_table.findOne(
{_id: new ObjectId(req.body.course_id)},
{projection: {
_id: 1,
"exams": {
"$map": {
"input": "$exams",
"in": {
"$this.exam_name": req.body.exam_name,
"students_exams": {
"$map": {
"input": "$$this.students_exams",
"in": { "student_email": req.body.student_email },
}},
},
}}
}
});
資料庫中一個條目的格式如下:中間的屬性塊是exams陣列中存盤的檔案(每個元素都是這樣)。下面的塊是檔案的格式。

uj5u.com熱心網友回復:
查詢 1
(展開)
- 你可以做一個嵌套的地圖和過濾器,但在這里我們只選擇 1 個考試,所以我猜資料很小,為了簡單起見,我們可以使用雙展開
- 匹配_id
- 放松
exams - 比賽
exam_name - 放松
student_exams - 比賽
email - 專案只保留
professor_notes和mark - 如果您最多只需要 1 個結果,請在最后再添加一個階段
{"limit" : 1}
測驗代碼在這里
aggregate(
[{"$match": {"$expr": {"$eq": ["$_id", 1]}}},
{"$unwind": {"path": "$exams"}},
{"$match": {"$expr": {"$eq": ["$exams.exam_name", "exam1"]}}},
{"$unwind": {"path": "$exams.student_exams"}},
{"$match":
{"$expr": {"$eq": ["$exams.student_exams.student_email", "email1"]}}},
{"$project":
{"_id": 0,
"professor_notes": "$exams.student_exams.professor_notes",
"mark": "$exams.student_exams.mark"}}])
Query2
(嵌套地圖/過濾器)
- map 如果不匹配 null else map 再次做同樣的事情
- 在回傳過濾器上洗掉空值
- 獲取第一個 , 中的第一個并替換 root
*查詢很大,它做同樣的事情,映射而不是展開,過濾而不是匹配(2 map/2 unwind ,2 filter/2 match)
測驗代碼在這里
aggregate(
[{"$match": {"$expr": {"$eq": ["$_id", 1]}}},
{"$replaceRoot":
{"newRoot":
{"$arrayElemAt":
[{"$arrayElemAt":
[{"$filter":
{"input":
{"$map":
{"input": "$exams",
"in":
{"$cond":
[{"$not": [{"$eq": ["$$exam.exam_name", "exam1"]}]}, null,
{"$filter":
{"input":
{"$map":
{"input": "$$exam.student_exams",
"in":
{"$cond":
[{"$not":
[{"$eq":
["$$students_exam.student_email", "email1"]}]},
null,
{"professor_notes":
"$$students_exam.professor_notes",
"mark": "$$students_exam.mark"}]},
"as": "students_exam"}},
"cond": {"$ne": ["$$students_exam", null]},
"as": "students_exam"}}]},
"as": "exam"}},
"cond": {"$ne": ["$$exam", null]},
"as": "exam"}}, 0]}, 0]}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372913.html
下一篇:在MongoDB中展開3個陣列
