- The problem is marks field having string type number, it requires in numeric type
- I have added
$project
stage and converted marks field to integer using $toInt
db.collection.aggregate([
{ $unwind: "$subjects" },
{ $match: { "subjects.paperName": "Maths" } },
{
$project: {
standard: 1,
marks: { $toInt: "$subjects.marks" }
}
},
{
$group: {
_id: "$standard",
SubjectsMarks: { $avg: "$marks" }
}
}
])
Playground
Second approach you can do all operations (filter subjects marks and convert to integer) in first stage using inside $project
$filter
to subjects
on the base of name,
$map
to iterate loop of result from above $filter
, and convert marks
to integer using $toInt
and return only marks
db.collection.aggregate([
{
$project: {
standard: 1,
marks: {
$map: {
input: {
$filter: {
input: "$subjects",
cond: { $eq: ["$$this.paperName", "Maths"] }
}
},
in: { $toInt: "$$this.marks" }
}
}
}
},
{ $unwind: "$marks" },
{
$group: {
_id: "$standard",
SubjectsMarks: { $avg: "$marks" }
}
}
])
Playground
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…