是否有可能比较MongoDB中单个Collection中的两个月数据?

时间:2015-03-10 12:29:30

标签: mongodb mongodb-query aggregation-framework

我有10 000 000条通话记录的收集数据库。 我想比较上个月到下个月的通话使用情况。

收集文件的例子

{
    "_id" : ObjectId("54ed74d76c68d23af73e230a"),
    "msisdn" : "9818441000",
    "callType" : "ISD"
    "duration" : 10.109999656677246,
    "charges" : 200,
    "traffic" : "Voice",
    "Date" : ISODate("2014-01-05T19:51:01.928Z")
}
{
    "_id" : ObjectId("54ed74d76c68d23af73e230b"),
    "msisdn" : "9818843796",
    "callType" : "Local",
    "duration" : 1,
    "charges" : 150,
    "traffic" : "Voice",
    "Date" : ISODate("2014-02-04T14:25:35.861Z") 

}

持续时间是我的用法。

我想将ISODate("2014-01-04T14:25:35.861Z")的持续时间与下个月ISODate("2014-02-04T14:25:35.861Z")的所有记录进行比较。

两个月内所有msisdn个数字相同。

1 个答案:

答案 0 :(得分:0)

这里明显的调用似乎是聚合数据,在MongoDB中聚合框架非常适合。以我在此处看到的一般用例字段为例。是的,我们通常用离散月来谈论,而不是假定从当前时间点开始一个月的某个值:

db.collection.aggregate([
    { "$match": {
        "msisdn": "9818441000",
        "Date": {
            "$gte": new Date("2014-01-01"),
            "$lt": new Date("2014-03-01")
        }
    }},
    { "$group": {
        "_id": {
            "year": { "$year": "$Date" },
            "month": { "$month": "$Date" },
            "callType": "$callType",
            "traffic": "$traffic"
        },
        "charges": { "$sum": "$charges" },
        "duration": { "$sum": "$duration" }
    }},
    { "$sort": { "_id": 1 } }
])

目的是在响应中生成两个记录,表示每个月的不同值。

您基本上可以获取这两个结果,并在客户端代码中比较它们之间的差异。

或者你可以在所有" MSISDN"在文档中成对分组的月份值:

db.collection.aggregate([
    { "$match": {
        "Date": {
            "$gte": new Date("2014-01-01"),
            "$lt": new Date("2014-03-01")
        }
    }},
    { "$group": {
        "_id": {
            "year": { "$year": "$Date" },
            "month": { "$month": "$Date" },
            "msisdn": "$msisdn",
            "callType": "$callType",
            "traffic": "$traffic"
        },
        "charges": { "$sum": "$charges" },
        "duration": { "$sum": "$duration" }
    }},
    { "$sort": { "_id": 1 } },
    { "$group": {
        "_id": { 
            "msisdn": "$_id.msisdn",
            "callType": "$_id.callType",
            "traffic": "$_id.traffic"
        },
        "data": { "$push": {
            "year": "$_id.year",
            "month": "$_id.month",
            "charges": "$charges",
            "duration": "$duration"
        }}
    }}
])
相关问题