How to Query Date With ISODate in MongoDB

Tahseen Tauseef Feb 02, 2024
  1. the Date() Method in MongoDB
  2. Behavior of the Date() Method
  3. Use the Date() Method in a Query in MongoDB
  4. Sort by Date in MongoDB
  5. Sort by Date Not Working in MongoDB
  6. Work Date Query With ISODate() in MongoDB
How to Query Date With ISODate in MongoDB

This MongoDB instructional post will explain the Date() method. Different approaches using date queries are described in this article.

the Date() Method in MongoDB

The Date() method returns the date as a string or a Date object.

  1. In MongoDB shell or mongosh, the Date() method returns the current date as a string.
  2. The new Date() function returns a Date object with the current date. The ISODate helper is wrapped around the Date object by mongosh, and the ISODate is in UTC (Universal Time).

You can use the new Date() function or the ISODate() method to define a specific date by giving an ISO-8601 date string with a year between '0' and '9999'. These functions accept the following formats.

  1. The ISODate with the supplied date is returned by the new Date("").
  2. The new Date("") specifies a DateTime in the client’s local time zone and returns an ISODate with that DateTime in UTC.
  3. The new Date("") takes a DateTime in UTC and returns a ISODate with that DateTime in UTC.
  4. new Date(integer>) returns an ISODate instance with the DateTime specified in milliseconds since the UNIX epoch (Jan 1, 1970).

Behavior of the Date() Method

Date objects are internally kept as a signed 64-bit integer that represents the milliseconds since the Unix epoch (Jan 1, 1970). All database procedures and drivers do not support the complete 64-bit range.

Dates with years in the inclusive range 0 through 9999 are safe to deal with.

Use the Date() Method in a Query in MongoDB

The following code adds a document with the field dateAdded set to the current date if no document with the _id equal to 1 exists in the products collection.

Code:

db.products.updateOne(
   { _id: 1 },
   {
     $set: { item: "apple" },
     $setOnInsert: { dateAdded: new Date() }
   },
   { upsert: true }
)

Use the Date() method to return the date as a string, as seen in the following example:

var myDateString = Date();

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 the Date object with the specified UTC DateTime.

var myDate = new Date("2016-05-18T16:00:00Z");

Sort by Date in MongoDB

The problem is solved using the sort() function and the $sort aggregate in MongoDB. You may sort the data in ascending or descending order with this tool.

Code Example:

db.posts.find().pretty()
{
    "_id" : 1,
    "title" : "MongoDB",
    "body" : "Hi there",
    "date" : "2021-01-01T00:00:00.000Z",
        "Country" : "United Kingdom"
}
{
    "_id" : 2,
    "title" : "MySQL",
    "body" : "Hello",
    "date" : ISODate("2020-01-01T00:00:00Z"),
        "Country" : "United States of America"
}
{
    "_id" : 3,
    "title" : "SQL",
    "body" : "World",
    "date" : ISODate("2021-01-01T00:00:00Z"),
        "Country" : "New Zealand"
}

Some data are added to the posts collection, and the date field is used to arrange them in ascending order, with earlier dates appearing first.

Code Example:

db.posts.find().sort({ date: 1 }).pretty()
{
    "_id" : 1,
    "title" : "MongoDB",
    "body" : "Hi there",
    "date" : "2021-01-01T00:00:00.000Z",
        "Country" : "United Kingdom"
}
{
    "_id" : 2,
    "title" : "MySQL",
    "body" : "Hello",
    "date" : ISODate("2020-01-01T00:00:00Z"),
        "Country" : "United States of America"
}
{
    "_id" : 3,
    "title" : "SQL",
    "body" : "World",
    "date" : ISODate("2021-01-01T00:00:00Z"),
        "Country" : "New Zealand"
}

After you’ve sorted it, note it because the first document has a date string rather than a date object.

The date string appears first, even if the date in document 2 is initialized later.

Sort by Date Not Working in MongoDB

There might be several reasons why MongoDB does not function, but you must remember a few procedures to operate with sort by date in MongoDB.

  1. Always remember that with help, you are storing the data in a collection.
  2. There are two ways to store the date field inside the document.
  3. Date() string and ISODate() data type are use to store date in documents.
  4. When you sort the date field using the sort() method, check which data type you used.

Code Example:

db.document.insertOne({ "productId" : 1001, "productDeliveryDateTime": new Date() });
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611c9e39e1fdc428cf238802")
}

The date is added using the Date() string, and the collection name is the document. You may insert a date in the document using ISODate() in the same way.

Work Date Query With ISODate() in MongoDB

Use the $gte operator and ISODate() to work date query with ISODate in MongoDB. Let’s make a collection using the document to better grasp the notion.

The following is the query to construct a collection with a document.

Query:

> db.dateDemo.insertOne({"StudentName":"John","StudentAge":26,"AdmissionDate":new ISODate("2013-06-07")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a65799064dcd4a68b70ea")
}

The find() function may display all documents in a collection.

Query:

db.dateDemo.find().pretty();

Output:

use find() function to display documents in a collection

Here is the date query using ISODate() in MongoDB.

Query:

> db.dateDemo.find({"AdmissionDate":{"$gte": ISODate("2013-06-07T00:00:00Z")}}).pretty();

Output:

Date query with ISODate() in MongoDB

Related Article - MongoDB Query