假設我有一個類似于學生字母等級的屬性,使用如下結構:
Students
{
"_id": {
"$oid": string
},
"student_id": int,
"grades": string,
"student_name": string,
...
}
我想遍歷資料庫并對學生進行分組,根據每個字母等級(假設每個學生都有一個唯一的名字)將他們存盤在集合中,例如:A :[Chris,Ada,Lee],A-:[John,麗莎],……我將如何通過使用 $addToSet 之類的東西來構造查詢(希望不必手動鍵入每個字母等級)?
我已經嘗試用 $group-ing 學生的成績并使用 $match 嘗試遍歷成績串列,但我還沒有遇到任何創建集合的無錯誤方法,而不僅僅是獲得有多少學生的整數計數那個成績(例如 7 名學生的成績為 A 。但是學生是誰?)。
uj5u.com熱心網友回復:
如果我明白你想做什么,這里有一種方法可以"$group"得到所有具有該等級"grades"的陣列。"student_name"
db.Students.aggregate([
{
"$group": {
"_id": "$grades",
"names": {"$push": "$student_name"},
"count": {"$count": {}}
}
}
])
在mongoplayground.net上試用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537282.html
標籤:数据库放分组聚合
