Search code examples
mongodbpymongo

MongoDB sort data by most number of records


I want to sort with the most occurrences of any value in a collection.

Eg.

{
  "id": "ID",
  "fruit": 'Apple'
}, 
{
  "id": "ID",
  "fruit": 'Banana'
}, 
{
  "id": "ID",
  "fruit": 'Apple'
}, 
{
  "id": "ID",
  "fruit": 'Orange'
}, 
{
  "id": "ID",
  "fruit": 'Apple'
}, 
{
  "id": "ID",
  "fruit": 'Banana'
}, 
{
  "id": "ID",
  "fruit": 'Apple'
}

I need fruit with the name Apple should on top because Apple occurs more time than other fruit in above collection


Solution

  • You could use the "$sortByCount" aggregation stage to accomplish this.

    db.collection.aggregate([
      {
        "$sortByCount": "$fruit"
      }
    ])
    

    Example output:

    [
      {
        "_id": "Apple",
        "count": 4
      },
      {
        "_id": "Banana",
        "count": 2
      },
      {
        "_id": "Orange",
        "count": 1
      }
    ]
    

    Try it on mongoplayground.net.