按出现次数对数组排序 mongodb

Sort an array by occurances mongodb

是否可以按出现次数对数组进行排序?

例如,给定

    {
        "_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"]
    }

我能够完成大部分的工作,但我不知道如何将它们重新组合成一个数组。

我一直在使用聚合管道

  1. $match开始寻找我想要的站点
  2. 然后 $unwind 使用路径:"$A"
  3. 下一个 $sortByCount"$A"
  4. ????我不知道如何将它们重新组合在一起。

这是管道:

[
    {
        '$match': {
            'site': 'www.xyz.ie'
        }
    }, {
        '$unwind': {
            'path': '$A'
        }
    }, {
        '$sortByCount': '$A'
    }, {
        ????
    }
]
  • $group nu _id and A,先获取site并统计总元素
  • $sortcount 降序排列
  • $group只用_id得到第一个site,构造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