How to save top count of array elements in mongoDB?

I am looking for a way to get the top two (or any other) numbers of a specific element from a given collection.

{"id": "xyz" , "fruits": ["Apple", "Mango"]} {"id": "abx", "fruits": ["Apple", "Banana"]} {"id" : "pqr", "fruits": ["Apple", "Mango"]} 

In the above example, the result would be: Apple and Mango , since the appearance of Apple (three times) is higher, and then Mango (two times). Do I need to use the Mongo map-reduce functions?

I am more inclined towards the performance and stability of the backend platform. How can I move forward if the "number of cases" occurs in real time?

Any help would be noticeable.

+5
source share
1 answer

You can use the unit. Here is a simple example that assumes that the meaning of the fruit will not be repeated within the same document:

 [ { $unwind: "$fruits" }, { $group: { _id: "$fruits", count: {$sum: 1} } }, { $sort: {count:-1} }, { $limit: 2 } ] 
+2
source

All Articles