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

203
Views
How to get a sorted list of most used values for a field in a mongodb collection

I have some documents resembling the following structure:

{ 
   "name": "item_1",
   "category": ["a", "b"]
},
{ 
   "name": "item_2",
   "category": ["c"]
},
{ 
   "name": "item_3",
   "category": ["a", "c"]
},
{ 
   "name": "item_4",
   "category": ["a"]
},
{ 
   "name": "item_5",
   "category": ["a"]
}

I'm trying to get a sorted list of the most used values for the category field in all documents within the collection.

So in this example, the return value I'm expecting should be something like this:

[
   {
      "category": "a",
      "count": 4
   },
   {
      "category": "c",
      "count": 2
   },
   {
      "category": "b",
      "count": 1
   }
]

Is there a way to make such a query in mongoose?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Demo - https://mongoplayground.net/p/sBpwwvowXLH

Use aggregation query to $unwind your category into separate documents $group them back by category and get the count

$sum

db.collection.aggregate({
  "$unwind": "$category"
},
{
  "$group": {
    "_id": "$category",
    count: { $sum: 1 }
  }
})
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!