Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Mongodb, aggregate nr of items in $group

I'm doing some aggregation to get some statistics on a how many products there are in cateories.

After some piping I'm down to this:

[
  {
     topCategory: "Computer",
     mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Laptop"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },
  {
    topCategory: "Computer",
    mainCategory: "Stationary"
  },

]

Wanted output:

[
  {
    name: "Computer",
    count: 4,
    mainCategories: [
      {
         name: "Laptop",
         count: 2
      },
      {
         name: "Stationary",
         count: 2
      }
    ]
  }
]

My query so far:

let query = mongoose.model('Product').aggregate([
    {
      $match:  {
        project:  mongoose.Types.ObjectId(req.params.projectId)
      }
    },
    { $project:  {
        _id: 0,
        topCategory: '$category.top',
        mainCategory: '$category.main',
      }
    },
 ]);

I know I need to use $group combined with $sum. I tried different way's but can't get it work.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In this case first you should group by mainCategory and then group by topCategory as below

db.collection.aggregate({
  $group: {
    _id: "$mainCategory",
    "count": {
      $sum: 1
    },
    "data": {
      "$push": "$$ROOT"
    }
  }
}, {
  "$unwind": "$data"
}, {
  "$group": {
    "_id": "$data.topCategory",
    "count": {
      "$sum": 1
    },
    "mainCategories": {
      "$addToSet": {
    "name": "$_id",
    "count": "$count"
      }
    }
  }
}).pretty()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!