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
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:
You could use the
"$sortByCount"
aggregation stage to accomplish this.Example output:
Try it on mongoplayground.net.