【问题标题】:Mongodb aggregation by day based on unix timestamp基于unix时间戳的mongodb按天聚合
【发布时间】:2015-10-12 10:23:07
【问题描述】:

我用谷歌搜索了很多,但没有找到任何有用的解决方案...我想找到每日用户总数。 我有一个名为 session_log 的集合,其中包含以下文档

{
    "_id" : ObjectId("52c690955d3cdd831504ce30"),
    "SORTID" : NumberLong(1388744853),
    "PLAYERID" : 3,
    "LASTLOGIN" : NumberLong(1388744461),
    "ISLOGIN" : 1,
    "LOGOUT" : NumberLong(1388744853)
}

我想从 LASTLOGIN 聚合...

这是我的查询:

db.session_log.aggregate(
    { $group : {
        _id: {
            LASTLOGIN : "$LASTLOGIN"
        },
        count: { $sum: 1 }
    }}
);

但它是按每次登录时间而不是每天汇总的。任何帮助将不胜感激

【问题讨论】:

  • 你用的是哪个mongo版本?

标签: mongodb nosql


【解决方案1】:

MongoDB 4.0 及更新版本

使用$toDate

db.session_log.aggregate([
    { "$group": {
        "_id": {
            "$dateToString": {
                "format": "%Y-%m-%d",
                "date": {
                    "$toDate": { 
                        "$multiply": [1000, "$LASTLOGIN"]
                    }
                }
            }
        },
        "count": { "$sum": 1 }
    } }
])

$convert

db.session_log.aggregate([
    { "$group": {
        "_id": {
            "$dateToString": {
                "format": "%Y-%m-%d",
                "date": {
                    "$convert": { 
                        "input":  { 
                            "$multiply": [1000, "$LASTLOGIN"] 
                        }, 
                        "to": "date"
                    }
                }
            }
        },
        "count": { "$sum": 1 }
    } }
])

MongoDB >= 3.0 和
db.session_log.aggregate([
    { "$group": {
        "_id": {
            "$dateToString": {
                "format": "%Y-%m-%d",
                "date": {
                    "$add": [
                        new Date(0), 
                        { "$multiply": [1000, "$LASTLOGIN"] }
                    ]
                }
            }
        },
        "count": { "$sum": 1 }
    } }
])

您需要将 LASTLOGIN 字段乘以 1000 以将其转换为毫秒时间戳

{ "$multiply": [1000, "$LASTLOGIN"] }

,然后转换为日期

"$add": [
    new Date(0),
    { "$multiply": [1000, "$LASTLOGIN"] }
]

这可以在 $project 管道中完成,方法是将您的毫秒时间添加到零毫秒 Date(0) 对象,然后提取 $year$month$dayOfMonth 部分来自转换后的日期,然后您可以在 $group 管道中使用这些部分来按天对文档进行分组.

因此,您应该将聚合管道更改为:

var project = {
    "$project":{ 
        "_id": 0,
        "y": {
            "$year": {
                "$add": [
                    new Date(0),
                    { "$multiply": [1000, "$LASTLOGIN"] }
                ]
            }
        },
        "m": {
            "$month": {
                "$add": [
                    new Date(0),
                    { "$multiply": [1000, "$LASTLOGIN"] }
                ]
            }
        }, 
        "d": {
            "$dayOfMonth": {
                "$add": [
                    new Date(0),
                    { "$multiply": [1000, "$LASTLOGIN"] }
                ]
            }
        }
    } 
},
group = {   
    "$group": { 
        "_id": { 
            "year": "$y", 
            "month": "$m", 
            "day": "$d"
        },  
        "count" : { "$sum" : 1 }
    }
};

运行聚合管道:

db.session_log.aggregate([ project, group ])

将给出以下结果(基于示例文档):

{ "_id" : { "year" : 2014, "month" : 1, "day" : 3 }, "count" : 1 }

一个改进是在单个管道中运行上述内容

var group = {   
    "$group": { 
        "_id": {    
            "year": {
                "$year": {
                    "$add": [
                        new Date(0),
                        { "$multiply": [1000, "$LASTLOGIN"] }
                    ]
                }
            },
            "mmonth": {
                "$month": {
                    "$add": [
                        new Date(0),
                        { "$multiply": [1000, "$LASTLOGIN"] }
                    ]
                }
            }, 
            "day": {
                "$dayOfMonth": {
                    "$add": [
                        new Date(0),
                        { "$multiply": [1000, "$LASTLOGIN"] }
                    ]
                }
            }
        },  
        "count" : { "$sum" : 1 }
    }
};

运行聚合管道:

db.session_log.aggregate([ group ])

【讨论】:

  • 您能否解释一下为什么我们需要所有这些数学体操来进行简单的类型转换,以使 mongo 与 Dates 一起工作,以及为什么我的解决方案 stackoverflow.com/questions/43451053/… 不起作用?
  • 使用这个 wave 得到类似“gmtime failed to convert time_t”的错误
  • @ChristianDecheryMongoDB 不允许从函数中插值管道变量/运算符,因为所有内容都在输入时解析为 BSON,即在管道内 MongoDB 将 BSON 运算符处理为原生 C++ 代码,因此 JavaScript 或其他任何东西都是不允许。
【解决方案2】:

第一件事是您的日期存储在timestamp,因此您需要先将timestamp 转换为ISODate,使用添加new Date(0) 并将timestamp 乘以1000,然后您将得到ISODate 之类的这个:

{"$add":[new Date(0),{"$multiply":[1000,"$LASTLOGIN"]}]} 这会将时间戳转换为 ISODate。

现在使用date aggregation,您需要使用$concatISODate 转换为所需格式,然后按最终格式日期分组,因此聚合查询将是:

db.session_log.aggregate({
  $project: {
    date: {
      $concat: [{
        $substr: [{
          $year: {
            "$add": [new Date(0), {
              "$multiply": [1000, "$LASTLOGIN"]
            }]
          }
        }, 0, 4]
      }, "/", {
        $substr: [{
          $month: {
            "$add": [new Date(0), {
              "$multiply": [1000, "$LASTLOGIN"]
            }]
          }
        }, 0, 4]
      }, "/", {
        $substr: [{
          $dayOfMonth: {
            "$add": [new Date(0), {
              "$multiply": [1000, "$LASTLOGIN"]
            }]
          }
        }, 0, 4]
      }]
    }
  }
}, {
  "$group": {
    "_id": "$date",
    "count": {
      "$sum": 1
    }
  }
})

如果你会使用 mongo 版本3.0 及以上版本,则使用dateToString 运算符将ISODate 转换为预定义格式,聚合查询为:

db.session_log.aggregate({
  "$project": {
    "ISODate": {
      "$add": [new Date(0), {
        "$multiply": [1000, "$LASTLOGIN"]
      }]
    }
  }
}, {
  "$project": {
    "yearMonthDay": {
      "$dateToString": {
        "format": "%Y-%m-%d",
        "date": "$ISODate"
      }
    }
  }
}, {
  "$group": {
    "_id": "$yearMonthDay",
    "count": {
      "$sum": 1
    }
  }
})

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 2021-03-02
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多