How to Query Date With ISODate in MongoDB
-
the
Date()
Method in MongoDB -
Behavior of the
Date()
Method -
Use the
Date()
Method in a Query in MongoDB - Sort by Date in MongoDB
- Sort by Date Not Working in MongoDB
-
Work Date Query 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.
- In MongoDB shell or mongosh, the
Date()
method returns the current date as a string. - The
new Date()
function returns aDate
object with the current date. The ISODate helper is wrapped around theDate
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.
- The
ISODate
with the supplied date is returned by thenew Date("")
. - The
new Date("")
specifies aDateTime
in the client’s local time zone and returns an ISODate with thatDateTime
in UTC. - The
new Date("")
takes aDateTime
in UTC and returns a ISODate with thatDateTime
in UTC. new Date(integer>)
returns an ISODate instance with theDateTime
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.
- Always remember that with help, you are storing the data in a collection.
- There are two ways to store the date field inside the document.
Date()
string andISODate()
data type are use to store date in documents.- 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:
Here is the date query using ISODate()
in MongoDB.
Query:
> db.dateDemo.find({"AdmissionDate":{"$gte": ISODate("2013-06-07T00:00:00Z")}}).pretty();
Output: