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

159
Views
mongodb GROUP BY and COUNT an Array within Document

Given: A single document in collection. The Document contains an array. (i.e. Only one document entry exist in Collection)

Expectation : perform group by on city and print counts

Sample Data:

{
name: "ABC Bank",
hospitalList: [
  {city: "Delhi", hspName: "EEE hospital"},
  {city: "Delhi", hspName: "FFF hospital"},
  {city: "Surat", hspName: "MMM hospital"},
  {city: "Noida", hspName: "GGG hospital"},
  {city: "Surat", hspName: "HHH hospital"},
  {city: "Surat", hspName: "NNN hospital"},
  {city: "Surat", hspName: "PPP hospital"},
]
}

Expected Output:

Delhi - 2
Noida - 1
Surat - 3

Tried (but did NOT work)

$group: {
  _id: "hospitalList.city",
  count: { $sum: 1 }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

  • $match - to match the document bank name
  • $unwind - split the array of object in own document
  • $group - to group it by city then calculate count
db.collection.aggregate([
  {
    $match: {
      name: "ABC Bank"
    }
  },
  {
    "$unwind": "$hospitalList"
  },
  {
    $group: {
      _id: "$hospitalList.city",
      count: {
        $sum: 1
      }
    }
  }
])

Mongo playground: https://mongoplayground.net/p/Ac7RkJd7vU9

as per expected output: Mongo playground: https://mongoplayground.net/p/zeqB7P-BYmI

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!