将iso日期转换为mongo查询中的时间戳 [英] convert iso date to timestamp in mongo query

查看:1217
本文介绍了将iso日期转换为mongo查询中的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是查询

[
    { 
        "$project": {
            "formattedDate": { 
                "$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" } 
            },
            "createdAtMonth": { "$month": "$ceatedAt" },
            "rating": 1
        }
    },
    {
         "$group": {
             "_id": "$formattedDate",
             "average": { "$avg": "$rating" },
             "month": { "$first": "$createdAtMonth" },
         }
    }
]

我需要时间戳的日期。如何做?

I need the date in timestamp. How to do that?

推荐答案

使用 $ subtract 您的日期为 minuend 新日期(1970-01-01) as subtrahend

db.collection.aggregate(
  {
    $project: { "timestamp": { $subtract: [ "$createdAt", new Date("1970-01-01") ] } } 
  }
);

对于文档

{ "_id": 1, "createdAt": ISODate("2016-09-01T14:35:14.952Z") }

结果是

{ "_id": 1, "timestamp": NumberLong("1472740514952") }

如果要按时间戳和(年,月,日) )您可以将时间戳记分割为一天中的毫秒数,因此每个时间戳都将是唯一的(而不是每毫秒)

If you want to group both by timestamp and (year, month, date) you can divide timestamp by the amount of milliseconds in a day, so that it will be unique for each day (and not for each millisecond)

db.collection.aggregate(
  {
    $project: 
      {
        "timestampByDay":
          {
            $floor: 
              {
                $divide: 
                  [ 
                    { $subtract: [ "$createdAt", new Date("1970-01-01") ] }, 
                    24 * 60 * 60 * 1000 
                  ] 
              }
          },
        "date": "$createdAt"
      }
  },
  {
    $group:
      {
        "_id": "$timestampByDay",
        "date": { $first: "$date" }
      }
  }
);

这篇关于将iso日期转换为mongo查询中的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆