我有一个系列"学生"。
{
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"}
怎么做? 请帮帮我。
答案 0 :(得分:1)
由于不支持排除,我不确定应该怎么做,我会使用另一个投影来包含所需的字段。 (这可能是一种更好的方法)。
让我们试试这个:
db.collection('studens').aggregate([
{$match: {"subjects.subject" : "Math" } },
{$project: {
_id:0,
subjects: {
$filter: {
input: '$subjects',
as: 'subjects',
cond: {$eq: ['$$subjects.subject', 'Math']}
}
}
}
},{$project: {subjects: { subject:1, score:1}}}
]);
结果:
"result" : [
{
"subjects" : [
{
"subject" : "Math",
"score" : "82"
}
]
},
{
"subjects" : [
{
"subject" : "Math",
"score" : "52"
}
]
}
]
这是你在找什么?