Home > front end >  MongoDB - Homework Help. How to group and count
MongoDB - Homework Help. How to group and count

Time:11-14

  1. For each subject type, list the name of the subject type and the total number of subjects that belong to the subject type.

Below is the database: Pastebin subject.js

What I've tried

For the first statement:

db.Subject.aggregate([{"$group":{"_id":"subject.$type","count":{"$sum":1}}}])
result: { "_id" : "subject.$type", "count" : 7 }
db.Subject.aggregate([{"$unwind":"$subject"},{"$group":{"_id":"$type"}}])
result: { "_id" : null }
db.Subject.aggregate([{"$unwind":"$subject"},{"$group":{"_id":{"subject.type":"$subject.type"}},"count":{"$sum":1}}])

CodePudding user response:

Group by _id with "$subject.type".

db.Subject.aggregate([
  {
    "$group": {
      "_id": "$subject.type",
      "count": {
        "$sum": 1
      }
    }
  }
])

Demo @ Mongo Playground

  • Related