如何在MongoDB中将时间戳转换为迄今为止



我正在研究MongoDB Collection的聚合。我的MongoDB Collection在时间戳记中具有Creation_time。我可以收集同一天的结果并与第二天的结果进行汇总。我必须收集数据以收集数据以收集数据的数据。5天。我的MongoDB系列是:

{
    "_id" : "1522845653126"
},
{
    "_id" : "1522838153324"
},
{
    "_id" : "1513421466415"
},
{
    "_id" : "1515488183153"
},
{
    "_id" : "1521571234500"
}

我该如何计算。在特定日期中有多少条目保存?nd假设我想要查询结果,以返回总计运行总计,例如:

{
 time: "2013-10-10"
 count: 3,
},
{
 time: "2013-10-11"
 total: 7,
}

这样的东西。我试图做这样的事情

db.coll.aggregate([
   {
        $group:{
        _id:new Date($creation_time).toLocaleDateString(),
         $count:{$add:1}
            }
         time:new Date($creation_time).toLocaleDateString()
   }
 ])

它不起作用。我在哪里做错了?我是MongoDB的新手。感谢您的任何帮助

您可以使用 $toDate 聚合将时间戳转换为ISO日期, $toLong 将字符串Timestamp转换为 mongodb中的integer timestamp3.6

db.collection.aggregate([
  { "$project": {
    "_id": {
      "$toDate": {
        "$toLong": "$_id"
      }
    }
  }},
  { "$group": {
    "_id": { "$dateToString": { "format": "%Y-%m-%d", "date": "$_id" } },
    "count": { "$sum": 1 }
  }}
])

尝试在这里

以及以前的版本

db.collection.aggregate([
  { "$project": {
    "date": { "$add": [ new Date(0), "$_id" ] }
  }}
])

在我的情况下,我用

db.collection.aggregate([
  { "$project": {
    "date": { "$toDate": { 
        $multiply:["$_id",1000 ]
             } 
       }
  }}
])

将时间戳从毫秒转换为秒。

最新更新