I have a collection named students and document as mentioned .All I need to find the avg marks of maths subject for each Standard

Viewed 31

Document:

{
    "_id":{"$oid":"5fe413b097d14d1fcd60bbc9"},
    "studentName":"Ajay Kumar",
    "standard":"6",
    "subjects":[
        {"paperName":"Maths","marks":"10"},
        {"paperName":"English","marks":"20"}]
}

Query:

db.Students.aggregate([{$unwind: "$subjects"},{$match:{"subjects.paperName":"Maths"}},{$group : {_id : "$standard", SubjectsMarks : {$avg : "$subjects.marks"}}}])

Output:

{ "_id" : "7", "SubjectsMarks" : null }
{ "_id" : "8", "SubjectsMarks" : null }
{ "_id" : "6", "SubjectsMarks" : null }

I have a collection named students and documents as mentioned. All I need to find the avg marks for maths subjects for each Standard.

what is wrong with this query?`

1 Answers
  • 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

Related