【问题标题】:How to maintain the top count(s) of array elements in mongoDB?如何维护 mongoDB 中数组元素的最高计数?
【发布时间】:2016-12-17 22:05:18
【问题描述】:

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

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

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

我更倾向于后端平台的性能和稳定性。如果“发生次数”是实时发生的,我该如何前进?

任何帮助都将不胜感激。

【问题讨论】:

    标签: mongodb mapreduce mongodb-query morphia


    【解决方案1】:

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

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

    【讨论】:

    • 为了提高性能,您可能希望首先投影“fruits”并禁用“_id”,因为它可以更好地使用索引
    猜你喜欢
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多