skip to Main Content

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

2

Answers


  1. You’ll need to use the aggregation framework to do that.

    You can use this MongoDB playground to test it, you need to run the following aggregation pipeline:

    db.collection.aggregate([
      {
        $group: {
          _id: "$fruit",
          count: {
            $sum: 1
          },
          documents: {
            $push: "$$ROOT"
          }
        }
      },
      {
        $sort: {
          count: -1
        }
      },
      {
        $unwind: {
          path: "$documents"
        }
      },
      {
        $replaceWith: "$documents"
      }
    ])
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search