您好,登錄后才能下訂單哦!
在日常中經常出現時間戳存在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 }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。