Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Mongodb timestamp to date format statistics

2024-12-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

In daily life, timestamps are often found in mongodb. Here is how to change the date format according to the timestamp.

Generate data

Db.test.insert ({"id": 20162, "create_time": 1554195600, "time": "2019-04-02 17:00:00"}); db.test.insert ({"id": 20159, "create_time": 1552635000, "time": "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"})

Query data

> 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": "14:55:00" {"_ id": ObjectId ("5d0c9095e07a14a96b41b7cd"), "id": 20158, "create_time": 1542798000 Time: "2018-11-21 19:00:00"}

Create_time queries by timestamp grouped by day

Db.test.aggregate ([{$project: {dt: {format: "% Y-%m-%d", date: {$add: [ISODate ("1970-01-01T00:00:00Z"), {$multiply: ["$create_time", 1000]}, {$group: {_ id: "$dt" Count: {$sum:1}},])

Query result

> 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}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report