【问题标题】:Group values by sub string in MongoDB在 MongoDB 中按子字符串对值进行分组
【发布时间】:2015-12-14 14:44:28
【问题描述】:

我的收藏中有这些文件:

{_id: "aaaaaaaa", email: "mail1@orange.fr"},
{_id: "bbbbbbbb", email: "mail2@orange.fr"},
{_id: "cccccccc", email: "mail3@orange.fr"},
{_id: "dddddddd", email: "mail4@gmail.com"},
{_id: "eeeeeeee", email: "mail5@gmail.com"},
{_id: "ffffffff", email: "mail6@yahoo.com"}

我想要这个结果:

{
    result: [
        {domain: "orange.fr", count: 3},
        {domain: "gmail.com", count: 2},
        {domain: "yahoo.com", count: 1},
    ]
}

我不确定你是否可以使用聚合器和 $regex 运算符

【问题讨论】:

  • 您是否已经尝试过?
  • 不,我在阅读聚合器文档后不知道

标签: mongodb mapreduce mongodb-query aggregation-framework


【解决方案1】:

聚合框架

我不相信使用当前的文档结构可以通过使用聚合框架来达到预期的结果。如果您将域名存储在单独的字段中,这将变得微不足道:

db.items.aggregate(
{
    $group:
    {
        _id: "$emailDomain",
        count: { $sum: 1 }
    },
}
)

Map-Reduce

使用简单的 map-reduce 聚合可以实现您想要的。自然,在大型集合上性能不会很好。

查询

db.emails.mapReduce(
    function() {
        if (this.email) {
            var parts = this.email.split('@');
            emit(parts[parts.length - 1], 1);
        }
    },
    function(key, values) {
        return Array.sum(values);
    },
    {
        out: { inline: 1 }
    }
)

输出

[
    {
        "_id" : "gmail.com",
        "value" : 2
    },
    {
        "_id" : "yahoo.com",
        "value" : 1
    },
    {
        "_id" : "orange.fr",
        "value" : 3
    }
]

【讨论】:

  • 一个专门的领域是一个被唤起的想法。但我想在没有的情况下进行测试。感谢您提供第二个解决方案。
  • 如果您来到这里并使用 DocumentDB(与 MongoDB 兼容)而不是“本机”MongoDB,可能不直接相关但很有帮助:DocumentDB 在撰写本文时不支持 MapReduce,因此您将不得不去使用聚合框架和单独的字段。
【解决方案2】:

聚合框架

MongoDB 3.4(2016 年 11 月 29 日发布)聚合框架中的 onwords 有很多方法

[
    {
        $project: {
            domain: {
                $substr: ["$email", {
                    $indexOfBytes: ["$email", "@"]
                }, {
                    $strLenBytes: "$email"
                }]
            }
    }, 
    {
        $group: {
            _id: '$domain',
            count: {
                $sum: 1
            }
        }
    },
    {
        $sort: {
            'count': -1
        }
    }, 
    {
        $group: {
            _id: null,
            result: {
                $push: {
                    'domain': "$_id",
                    'count': '$count'
                }
            }
        }
    }
]

结果

{
    _id: null,
    result: [
        {domain: "@orange.fr", count: 3},
        {domain: "@gmail.com", count: 2},
        {domain: "@yahoo.com", count: 1},
    ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多