convert iso date to timestamp in mongo query

2020-01-29 07:59发布

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?

2条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-29 08:31

Mongodb 4.0 has introduced $toLong aggregation which convert date to timestamp

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

You can try it here

查看更多
▲ chillily
3楼-- · 2020-01-29 08:51

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" }
      }
  }
);
查看更多
登录 后发表回答