如何维护 mongoDB 中数组元素的最高计数?

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

我正在寻找一种方法来获取给定集合中特定元素的前两个(或任何其他数字)计数。

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

对于上面的示例,结果将是:Apple and Mango 因为 Apple(三次)的出现率较高,其次是 Mango(两次)。我需要使用 Mongo map-reduce 功能吗?

我更倾向于后端平台的性能和稳定性。如果 "number of occurrence" 实时发生,我该如何前进?

任何帮助都将不胜感激。

你可以使用聚合。这是一个简单的例子,假设一个水果值不会在单个文档中重复:

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