我有一個集合「學生」。如何在對象中獲取一些字段?
{
student:"Jone Doe",
class:"A",
subjects:
[
{subject:"Math",teacher:"Linda","score":"82"},
{subject:"English",teacher:"Jone","score":"52"},
{subject:"History",teacher:"Maria","score":"32"},
]
}
{
student:"Baby Doe",
class:"B",
subjects:
[
{subject:"Math",teacher:"Hilary","score":"52"},
{subject:"English",teacher:"Notham","score":"52"},
{subject:"History",teacher:"Hamet","score":"32"},
]
}
我想獲得學生的學科「數學」的所有分數。
即時通訊使用aggregation
得到
db.collection('studens').aggregate([
{$match: {"subjects.subject" : "Math" } },
{$project: {
_id:0,
subjects: {
$filter: {
input: "$subjects",
as: "subject",
cond: { $lte: [ "$$subject.subject", "Math" ] }
}
}
}
}
]);
而結果:
{subject:"Math",teacher:"Linda","score":"82"}
{subject:"Math",teacher:"Hilary","score":"52"}
但它顯示的所有字段,我要的結果(只顯示主題和得分):
{subject:"Math","score":"82"}
{subject:"Math","score":"52"}
如何做到這一點? 請幫幫我。
好吧,但是我只是測試你的聚集..我得到:' 「結果」:[{ 「科目」: //所有值 ] },{ 「科目」: //所有值甚至英文和其他主題 ] } ]'這是你所得到的? – rahpuser
將條件更改爲$ eq,現在我只得到數學主題文檔..這是您正在尋找的輸出嗎?不支持排除值,所以..你可以嘗試使用包含字段 – rahpuser