Bryead
Bryead

Reputation: 120

MongoDB - How to group and count

  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}}])

Upvotes: 1

Views: 74

Answers (1)

Yong Shun
Yong Shun

Reputation: 51125

Group by _id with "$subject.type".

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

Demo @ Mongo Playground

Upvotes: 3

Related Questions