【问题标题】:MongoDB mapReduce per minute document count segregated by an additional category fieldMongoDB mapReduce 每分钟文档计数由附加类别字段分隔
【发布时间】:2018-03-12 02:48:52
【问题描述】:

我有一个具有以下架构的 MongoDB 集合:

const MessageSchema = {
 message: {type: String},
 category: {type String, allowedValues: ['a', 'b', 'c', 'd', 'e']},
 createdAt: {type: Date}
}

这些消息文档是按随机时间间隔创建的。我想创建图表所需的数据集,该图表绘制每个类别的每分钟消息数(计数)。输出将是带有键 time, a.count, b.count, c.count, d.counte.count 的对象数组。生成的数据集应仅考虑上周的数据,而不是更早的数据。

数据集可能非常大。

我想我可以用db.collection.mapReduce 做到这一点。我找到了一个适用于所有消息的解决方案,但没有按类别分开。指向正确方向的指针将不胜感激。

【问题讨论】:

  • 你看过聚合吗? $group?

标签: javascript mongodb hadoop mapreduce nosql


【解决方案1】:

当您可以通过简单的聚合来做到这一点时,没有理由使用 mapReduce:

db.messages.aggregate([
  {$match: { createdAt: { $gte: ISODate('2018-01-01') } }},
  {$group: {
        _id: {date: {$dateFromParts:{
                year: { $year: "$createdAt" },
                month: { $month: "$createdAt" },
                day: { $dayOfMonth: "$createdAt" },
                hour: { $dayOfMonth: "$createdAt" },
                minute: { $minute: "$createdAt" }
             }},
             category: "$category"
        },
        count: { $sum: 1 }
    }
  }
])

【讨论】:

    【解决方案2】:

    您可以为此使用MongoDB Aggregation framework,方法是匹配createdAt 之后发生的记录,然后按category 分组:

    db.getCollection('messages').aggregate([{
            $match: { createdAt: { $gte: ISODate('2018-10-10') } }
        },
        {
            $group: {
                _id: {
                    year: { $year: "$createdAt" },
                    day: { $dayOfYear: "$createdAt" },
                    minute: { $minute: "$createdAt" },
                },
                categories: { $push: "$category" }
            }
        },
        { $unwind: "$categories" },
        {
            $group: {
                _id: { interval: "$_id", category: "$categories" },
                count: { $sum: 1 }
            }
        },
        { 
            $group: {
                _id: "$_id.interval",
                category_count: {
                    $push: { category: "$_id.category", count: "$count" }
                }
            }
        }
    ])
    

    【讨论】:

    • 我如何创建每分钟间隔的计数?我是否将聚合函数的输出输入 mapReduce?感谢您的快速回答。
    猜你喜欢
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    相关资源
    最近更新 更多