MongoDB Date Query

MongoDB Date() Query is used to get the date string or Date Object in a specified format.

In this tutorial, we will learn how to use Date() query with the help of examples.

MongoDB Date as String

To get the date as a string, use Date() command in Mongo Shell or in a Query without new keyword prior to Date() command.

ADVERTISEMENT

Example – Date() in Mongo Shell

Running Date() command in Mongo Shell returns Date as String.

Mongo Shell Date Query

In Mongo Shell, Date() command returns date string formatted in UTC.

Date() in Mongo Script

Create a JavaScript file named, dateExample.js in the bin directory and copy the following content to dateExample.js.

dateExample.js

// read Date as String
var date = Date()

print("=======Date=======")
// print date
print(date)

Run the Mongo Script file using mongo command in cmd or terminal as shown below.

Mongo Date command in Script

Mongo Date Object

The Date can be obtained as an object in MongoDB using new keyword prior to Date() command.

Date Object in Mongo Shell

Mongo Date Object in Shell

The difference between Date and new Date() might not be quite obvious with the above example. The reason being that Mongo Shell converts Date object to string while echoing to the screen. Using typeof() function we can clear the thoughts on Date type using typeof(Date()) and typeof(new Date()).

Mongo Date String and Object

By storing the Date object in a variable, we can access its properties using functions like getFullYear(), getMinutes(), etc.

Mongo Date Object Usage

Mongo Date Formats

While creating a new Date() object, you can specify the date format.

Following are the allowed date formats and each of them returns the resulting ISODate instance.

  • new Date(“<YYYY-mm-dd>”)
  • new Date(“<YYYY-mm-ddTHH:MM:ss>”)
  • new Date(“<YYYY-mm-ddTHH:MM:ssZ>”)
  • new Date(<milliseconds>) where <milliseconds> is an integer and specifies the number of milliseconds since the Unix epoch (Jan 1, 1970).

Following Mongo Script demonstrates the usage of Date Formats.

dateExample.js

var date1 = new Date("2018-07-14")
var date2 = new Date("2016-05-22T10:05:44")
var date3 = new Date("2016-05-25T10:05:44Z")
var date4 = new Date(1524632175894)

print("------printing dates in different formats-------")
print(date1)
print(date2)
print(date3)
print(date4)

Output

MongoDB Date Formats

Conclusion

In this MongoDB Tutorial, we have learned the usage of Mongo Date() and its usage as a String and Object.