Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain the top count(s) of array elements in mongoDB?

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.

like image 549
Amit Pal Avatar asked Oct 30 '22 22:10

Amit Pal


1 Answers

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
    }
]
like image 191
Wake Avatar answered Nov 15 '22 00:11

Wake