mongodb - 使用 mongodb 聚合框架按数组长度分组

标签 mongodb mapreduce aggregation-framework

我有一个看起来像这样的集合:

{
    "_id": "id0",
    "name": "...",
    "saved_things": [
        { ... },
        { ... },
        { ... },
    ]
}
{
    "_id": "id1",
    "name": "...",
    "saved_things": [
        { ... },
    ]
}
{
    "_id": "id2",
    "name": "...",
    "saved_things": [
        { ... },
    ]
}

等等……

我想使用 mongodb 的聚合框架来得出一个直方图结果,该结果告诉有多少用户拥有一定数量的 saved_things。例如,对于上面的数据集,它可能会返回如下内容:

{ "_id": 1, "count": 2 },
{ "_id": 3, "count": 1 }

我尝试了各种聚合函数组合,如下所示,但没有一个能正确运行。 (我觉得我要解决这个非常错误的问题。)

collection.aggregate([
    { $unwind: "$saved_things" },
    { $group: "$_id", count: { $sum: 1 } } },
    { $group: "$count", number: { $sum: 1 } } },
    { $sort: { number: -1 } }
], function(err, result) {
    console.log(result);
});

这可以通过 Mongo 的聚合框架实现,还是使用 map reduce 函数会更好?

最佳答案

好的,知道了!开始了。聚合管道基本上是这样的:

{
    $unwind: "$saved_things"
},
{
    $group: {
        _id: "$_id",
        size: {
            $sum: 1
        }
    }
},
{
    $group: {
        _id: "$size",
        frequency: {
            $sum: 1
        }
    }
},
{
    $project: {
        size: "$_id",
        frequency: 1,
        _id: 0
    }
}

展开saved_things数组,然后按文档_id分组并统计,就可以得到数组的大小。现在很容易,按 size 分组并计算频率。使用项目将 _id 字段重命名为 size

关于mongodb - 使用 mongodb 聚合框架按数组长度分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17955072/

相关文章:

mongodb - Google Cloud Platform - 无法连接到 mongodb

hadoop - Hadoop MapReduce的项目构想

arrays - 仅查询嵌套数组中的数字

mongodb - 如何在 MongoDB 中执行超前和滞后

node.js - 如何在 MongoDB 的数组字段中投影特定元素?

javascript - MongoDB C# 以及如何使用 javascript 从客户端更新

mongodb - MongoDB中存储小整数的方法

python - 将装饰器与 MapReduce 映射器/缩减器函数一起使用?

hadoop - Hadoop中的MapReduce作业的物理进程树(在群集节点上)

node.js - 如何在 Mongoose /Node 中获得平均评分