Skip to content
Advertisement

Sort an array by occurances mongodb

Is it possible to sort an array by occurrences?

For Example, given

JavaScript

return

JavaScript

I am able to get it most of the way there but I cannot figure out how to join them all back together in an array.

I have been using an aggregation pipeline

  1. Starting with $match to find the site I want
  2. Then $unwind on with path: "$A"
  3. Next $sortByCount on "$A"
  4. ???? I can’t figure out how to group it all back together.

Here is the pipeline:

JavaScript

Advertisement

Answer

  • $group nu _id and A, get first site and count total elements
  • $sort by count in descending order
  • $group by only _id and get first site, and construct array of A
JavaScript

Playground

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement