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

Viewed 55

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?

1 Answers
Related