mongodb 在mongo查询中将iso日期转换为时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39274311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:49:15  来源:igfitidea点击:

convert iso date to timestamp in mongo query

mongodbdatemongodb-queryaggregation-framework

提问by nirvair

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?

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

回答by tarashypka

Use $subtractarithmetic aggregation operatorwith your Date as minuendand new Date("1970-01-01")as subtrahend.

使用算术集成算你的日期作为被减数,并作为减数$subtractnew Date("1970-01-01")

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

回答by Ashh

Mongodb 4.0has introduced $toLongaggregation which convert date to timestamp

Mongodb 4.0引入了$toLong将日期转换为时间戳的聚合

db.collection.aggregate([
  { "$project": {
    "createdAt": {
      "$toLong": "$createdAt"
    }
  }}
])

You can try it here

你可以在这里试试