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

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

问题描述

这里是查询

<预><代码>[{$项目":{格式化日期":{"$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" }},"createdAtMonth": { "$month": "$ceatedAt" },评分":1}},{$ 组":{"_id": "$formattedDate",平均":{$avg":$rating"},"月": { "$first": "$createdAtMonth" },}}]

我需要时间戳中的日期.怎么做?

解决方案

使用 $subtract 算术聚合运算符,您的日期为 minuendnew Date("1970-01-01") 作为减数.

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

如果你想同时按时间戳和(年、月、日)分组,你可以用时间戳除以一天中的毫秒数,这样它对于每一天都是唯一的(而不是每一毫秒)

db.collection.aggregate({$项目:{timestampByDay":{$楼:{$除:[{ $subtract: [ "$createdAt", new Date("1970-01-01") ] },24*60*60*1000]}},日期":$createdAt"}},{$组:{"_id": "$timestampByDay",日期":{ $first:$date"}}});

here is the query

[
    { 
        "$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?

解决方案

Use $subtract arithmetic aggregation operator with your Date as minuend and new Date("1970-01-01") as subtrahend.

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

For document

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

the result is

{ "_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" }
      }
  }
);

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

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