- Reference >
mongo
Shell Methods >- Object Constructors and Methods >
- Date()
Date()¶
-
Date
()¶ Returns a date either as a string or as a Date object.
Date()
returns the current date as a string in themongo
shell.new Date()
returns the current date as a Date object. Themongo
shell wraps the Date object with theISODate
helper. TheISODate
is in UTC.
You can specify a particular date by passing to the
Date()
method a datetime string. For example:new Date("<YYYY-mm-dd>")
which returns theISODate
with the specified date.new Date("<YYYY-mm-ddTHH:MM:ss>")
which specifies the datetime in local datetime and returns theISODate
with the specified datetime in UTC.new Date("<YYYY-mm-ddTHH:MM:ssZ>")
which specifies the datetime in UTC and returns theISODate
with the specified datetime in UTC.
Behavior¶
Internally, Date objects are stored as a 64 bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970), which results in a representable date range of about 290 millions years into the past and future.
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.update(
{ _id: 1 },
{
$set: { item: "apple" },
$setOnInsert: { dateAdded: new Date() }
},
{ upsert: true }
)
See also
Return Date as a String¶
To return the date as a string, use the Date()
method, as in the
following example:
var myDateString = Date();