convert iso date to timestamp in mongo query

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?


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

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

You can try it here


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

If you want to update timestamp. with the current date and time use the below query.

db.getCollection('movie').update(
{"applicationId":"2b5958d9629026491c30b42f2d5256fa8","type":"shortcut"},
{$set : {userName:"[email protected]",created_at: NumberLong(new Date()),"updated_at":NumberLong(new Date()),"docIndex":UUID()}}, {multi:true, upsert: false}
)