mongodb group by date 聚合查询日期 统计每天数据(信息量)

/* 1 */
{
    "_id" : ObjectId("557ac1e2153c43c320393d9d"),
    "msgType" : "text",
    "sendTime" : ISODate("2015-06-12T11:26:26.000Z")
}

/* 2 */
{
    "_id" : ObjectId("557ac1ee153c43c320393d9e"),
    "msgType" : "text",
    "sendTime" : ISODate("2015-06-12T11:26:38.000Z")
}

/* 3 */
{
    "_id" : ObjectId("557ac2012de5d32d213963b5"),
    "msgType" : "text",
    "sendTime" : ISODate("2015-06-12T11:26:56.000Z")
}

/* 4 */
{
    "_id" : ObjectId("557ac978bb31196e21d23868"),
    "msgType" : "text",
    "sendTime" : ISODate("2015-06-12T11:58:47.000Z")
}

/* 5 */
{
    "_id" : ObjectId("557ac9afbb31196e21d23869"),
    "msgType" : "text",
    "sendTime" : ISODate("2015-06-12T11:59:43.000Z")
}


// SQL Here
db.getCollection('wechat_message').aggregate(
    [   
        {   $project : { day : {$substr: ["$sendTime", 0, 10] }}},        
        {   $group   : { _id : "$day",  number : { $sum : 1 }}},
        {   $sort    : { _id : -1 }}        
    ]
)


// Result Here
"result" : [ 
        {
            "_id" : "2015-07-06",
            "number" : 13.0000000000000000
        }, 
        {
            "_id" : "2015-07-05",
            "number" : 3.0000000000000000
        }, 
        {
            "_id" : "2015-07-03",
            "number" : 10.0000000000000000
        }, 
        {
            "_id" : "2015-07-02",
            "number" : 29.0000000000000000
        },

更多实例应用扫码体验:

mongodb group by date 聚合查询日期 统计每天数据(信息量)

相关推荐