Skip to content
Advertisement

Sort an array by occurances mongodb

Is it possible to sort an array by occurrences?

For Example, given

    {
        "_id": {
            "$oid": "60d20d342c7951852a21s53a"
            },
        "site": "www.xyz.ie",
        "A": ["mary", "jamie", "john", "mary", "mary", "john"], 
    }

return

    {
        "_id": {
            "$oid": "60d20d342c7951852a21s53a"
            },
        "site": "www.xyz.ie",
        "A": ["mary", "jamie", "john", "mary", "mary", "john"], 
        "sorted_A" : ["mary","john","jamie"]
    }

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:

[
    {
        '$match': {
            'site': 'www.xyz.ie'
        }
    }, {
        '$unwind': {
            'path': '$A'
        }
    }, {
        '$sortByCount': '$A'
    }, {
        ????
    }
]

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
[
  { $match: { site: "www.xyz.ie" } },
  { $unwind: "$A" },
  {
    $group: {
      _id: { _id: "$_id", A: "$A" },
      site: { $first: "$site" },
      count: { $sum: 1 }
    }
  },
  { $sort: { count: -1 } },
  {
    $group: {
      _id: "$_id._id",
      site: { $first: "$site" },
      A: { $push: "$_id.A" }
    }
  }
]

Playground

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