我有一个集合“学生”。如何在对象中获取一些字段?
{
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