convert iso date to timestamp in mongo query

后端 未结 3 793
夕颜
夕颜 2020-11-30 09:43

here is the query

[
    { 
        \"$project\": {
            \"formattedDate\": { 
                \"$dateToString\": { \"format\": \"%Y-%m-%d\", \"date\":         


        
3条回答
  •  甜味超标
    2020-11-30 10:13

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

提交回复
热议问题