Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

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

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?`

question from:https://stackoverflow.com/questions/65516806/i-have-a-collection-named-students-and-document-as-mentioned-all-i-need-to-find

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...