I am looking a way to get the top two (or any other number) counts of a specific element from the given collection.
{"id": "xyz" , "fruits": ["Apple", "Mango"]}
{"id": "abx", "fruits": ["Apple", "Banana"]}
{"id" : "pqr", "fruits": ["Apple", "Mango"]}
For above example, the result would be: Apple and Mango
because the occurrence of Apple
(three times) is higher followed by Mango
(two times). Do I need to go with Mongo map-reduce
functionality?
I am more leaned towards the performance and stability of backend platform. How can I move forward if the "number of occurrence" is happening real time?
Any help would be appreciable.
You could use aggregate. Here is a simple example which assumes that a fruit value will not be repeated within a single document:
[
{
$unwind: "$fruits"
},
{
$group: {
_id: "$fruits",
count: {$sum: 1}
}
},
{
$sort: {count:-1}
},
{
$limit: 2
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With