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
CodePudding user response:
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.
CodePudding user response:
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"
}
])