Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 653
nirvair Avatar asked Sep 01 '16 14:09

nirvair


People also ask

How do I change the ISO Date in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

How do I query a Date in MongoDB?

How does Date Query work in MongoDB? We can use date () command to get a date as a string in a query without the new keyword or MongoDB shell. While creating a new date object, we can specify the date object as follows.

What format are MongoDB timestamps?

Timestamps. BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where: the most significant 32 bits are a time_t value (seconds since the Unix epoch)

Does MongoDB store timestamp?

MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.


2 Answers

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

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

You can try it here

like image 107
Ashh Avatar answered Sep 30 '22 11:09

Ashh


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" }
      }
  }
);
like image 22
tarashypka Avatar answered Sep 30 '22 10:09

tarashypka