Date()
Date()
Returns a date either as a string or as a Date object.
Date()
returns the current date as a string inmongosh
.new Date()
returns the current date as a Date object.mongosh
wraps the Date object with theISODate
helper. TheISODate
is in UTC.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range
0
through9999
to thenew Date()
constructor or theISODate()
function. These functions accept the following formats:new Date("<YYYY-mm-dd>")
returns theISODate
with the specified date.new Date("<YYYY-mm-ddTHH:MM:ss>")
specifies the datetime in the client's local timezone and returns theISODate
with the specified datetime in UTC.new Date("<YYYY-mm-ddTHH:MM:ssZ>")
specifies the datetime in UTC and returns theISODate
with the specified datetime in UTC.new Date(<integer>)
specifies the datetime as milliseconds since the UNIX epoch (Jan 1, 1970), and returns the resultingISODate
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:
db.products.updateOne( { _id: 1 }, { $set: { item: "apple" }, $setOnInsert: { dateAdded: new Date() } }, { upsert: true } )
Return Date as a String
To return the date as a string, use the Date()
method, as in the
following example:
var myDateString = Date();
Return Date as Date
Object
mongosh
wraps objects of
Date type with the ISODate
helper;
however, the objects remain of type Date.
The following example uses new Date()
to return
Date object with the specified UTC datetime.
var myDate = new Date("2016-05-18T16:00:00Z");
Insert and Return ISODate
Objects
You can specify dates as ISODate
objects.
The following example creates a cakeSales
collection with
ISODate
objects in the orderDate
field:
db.cakeSales.insertMany( [ { _id: 0, type: "chocolate", orderDate: new ISODate("2020-05-18T14:10:30Z") }, { _id: 1, type: "strawberry", orderDate: new ISODate("2021-03-20T11:30:05Z") }, { _id: 2, type: "vanilla", orderDate: new ISODate("2021-01-15T06:31:15Z") } ] )
The following example returns documents where the orderDate
is less
than the ISODate
specified in the $lt
operator:
db.cakeSales.find( { orderDate: { $lt: ISODate("2021-02-25T10:03:46.000Z") } } )
Example output:
[ { _id: 0, type: 'chocolate', orderDate: ISODate("2020-05-18T14:10:30.000Z") }, { _id: 2, type: 'vanilla', orderDate: ISODate("2021-01-15T06:31:15.000Z") } ]