mongodb时间戳转日期格式统计
在日常中经常出现时间戳存在MongoDB里的情况,以下就是根据时间戳转日期格式
为庆城等地区用户提供了全套网页设计制作服务,及庆城网站建设行业解决方案。主营业务为成都网站制作、成都做网站、庆城网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
生成数据
db.test.insert({ "id":20162,"create_time":1554195600,"time":"2019-04-02 17:00:00"});
db.test.insert({ "id":20159,"create_time":1552635000,"time":"2019-03-15 15:30:00"});
db.test.insert({ "id":20160,"create_time":1552632900,"time":"2019-03-15 14:55:00"});
db.test.insert({ "id":20161,"create_time":1552632900,"time":"2019-03-15 14:55:00"});
db.test.insert({ "id":20158,"create_time":1542798000,"time":"2018-11-21 19:00:00"});
查询数据
> db.test.find();
{ "_id" : ObjectId("5d0c9094e07a14a96b41b7c9"), "id" : 20162, "create_time" : 1554195600, "time" : "2019-04-02 17:00:00" }
{ "_id" : ObjectId("5d0c9094e07a14a96b41b7ca"), "id" : 20159, "create_time" : 1552635000, "time" : "2019-03-15 15:30:00" }
{ "_id" : ObjectId("5d0c9094e07a14a96b41b7cb"), "id" : 20160, "create_time" : 1552632900, "time" : "2019-03-15 14:55:00" }
{ "_id" : ObjectId("5d0c9094e07a14a96b41b7cc"), "id" : 20161, "create_time" : 1552632900, "time" : "2019-03-15 14:55:00" }
{ "_id" : ObjectId("5d0c9095e07a14a96b41b7cd"), "id" : 20158, "create_time" : 1542798000, "time" : "2018-11-21 19:00:00" }
按时间戳create_time查询按天分组
db.test.aggregate( [{
$project: {
dt:{$dateToString:{format:"%Y-%m-%d",date:{$add:[ISODate("1970-01-01T00:00:00Z"),{$multiply:["$create_time",1000]}]}}}
}},{
$group: {
_id:"$dt"
,count:{$sum:1}
}},]);
查询结果
> db.test.aggregate( [{
... $project: {
... dt:{$dateToString:{format:"%Y-%m-%d",date:{$add:[ISODate("1970-01-01T00:00:00Z"),{$multiply:["$create_time",1000]}]}}}
... }},{
... $group: {
... _id:"$dt"
... ,count:{$sum:1}
... }},]);
{ "_id" : "2018-11-21", "count" : 1 }
{ "_id" : "2019-03-15", "count" : 3 }
{ "_id" : "2019-04-02", "count" : 1 }
网页题目:mongodb时间戳转日期格式统计
本文来源:http://azwzsj.com/article/gihijg.html