MongoDB Data Types What is Date and ISODate in MongoDB
Date and ISODate in MongoDB
In MongoDB, ISODate is used to store date objects in ISO 8601 format, which is a standard for date and time representation. The ISODate is often used for handling date fields within MongoDB documents.
Syntax
You can specify either of the following formats: Date() returns the current date as a string in mongosh. new Date() returns the current date as a Date object. mongosh wraps the Date object with the ISODate helper. The ISODate is in UTC. 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.
- new Date("YYYY-mm-ddTHH:MM:ss") specifies the datetime in the client's local timezone and returns the ISODate with the specified datetime in UTC.
- new Date("YYYY-mm-ddTHH:MM:ssZ") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
- new Date(<integer>) specifies the datetime as milliseconds since the UNIX epoch (Jan 1, 1970), and returns the resulting ISODate instance.
Behavior
Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).
Not all database operations and drivers support the full 64-bit range. You may safely work with dates with years within the inclusive range 0 through 9999.
Examples
Use Date in a Query If no document with _id equal to 1 exists in the products collection, the following operation inserts a document with the field dateAdded set to the current date:
const timeAsMillisecond = Date.parse("2024-07-23 03:12:52");
const timeAsSecond = timeAsMillisecond / 1000;
console.log({
timeAsMillisecond,
timeAsSecond,
myDate: new Date(timeAsMillisecond) // ISODate("2024-07-23T03:12:52.000+07:00")
})
db.cakeSales.insertMany( [
{ _id: 0, type: "input with full date1", orderDate: new ISODate("2020-05-18T14:10:30Z") },
{ _id: 1, type: "input with full date2", orderDate: new ISODate("2021-03-20T11:30:05Z") },
{ _id: 2, type: "input with full date3", orderDate: new ISODate("2021-01-15T06:31:15Z") },
{ _id: 3, type: "my1 only date", orderDate: new ISODate("2021-01-15") },
{ _id: 4, type: "my2 date and hour:minute:second", orderDate: new ISODate("2021-01-15T08:00:00") },
{ _id: 5, type: "my3 date as a number", orderDate: new Date(timeAsMillisecond) },
] )
db.cakeSales.find({})
.projection({})
.sort({_id:-1})
.limit(100)
All rights reserved