Using ISODate for date queries in MongoDB
This MongoDB tutorial article will explain Date()
the methods. This article introduces different ways to query using dates.
Date() Method in MongoDB
Date()
The method returns the date as a string or a Date object.
- In the MongoDB shell or mongosh, the Date() method returns the current date as a string.
- The new Date() function returns a Date object containing the current date. The ISODate helper is wrapped by mongosh around the Date object. ISODate is in UTC (Coordinated Universal Time).
You can use the new Date()
function or ISODate()
method to define a specific date by providing an ISO-8601 date string with a year between "0" and "9999". These functions accept the following formats.
- An ISODate with the supplied date is returned by new Date("").
- new Date("") specifies a DateTime in the client's local time zone and returns an ISODate and a DateTime in UTC.
- new Date("") takes a DateTime in UTC format and returns an ISODate with the DateTime in UTC format.
- new Date(integer>) Returns an ISODate instance where the DateTime specifies the number of milliseconds since the UNIX epoch (January 1, 1970).
Date() Method Behavior
Date objects are stored internally as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (January 1, 1970). Not all database procedures and drivers support the full 64-bit range.
Dates with years between 0 and 9999 can be handled safely.
Using the Date() method in MongoDB queries
_id
If a document with date equal to 1
does not exist in the products collection , the following code adds a document and sets the field dateAdded to the current date.
Code:
db.products.updateOne(
{ _id: 1 },
{
$set: { item: "apple" },
$setOnInsert: { dateAdded: new Date() }
},
{ upsert: true }
)
Use Date()
the method to return a date as a string, as the following example shows:
var myDateString = Date();
mongosh uses the ISODate helper to wrap objects of type Date. However, the objects are still of type Date.
The following example uses new Date()
to return a Date object with the specified UTC date-time.
var myDate = new Date("2016-05-18T16:00:00Z");
Sorting by date in MongoDB
This problem is solved using the sort() function and the $sort aggregation in MongoDB. You can use this tool to sort the data in ascending or descending order.
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 is added to the posts collection, and the date field is used to sort them in ascending order, with older dates 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 sorting, notice it because the first document has a date string instead of a date object.
The date string appears first, even though the date in document 2 was initialized later.
Sorting by date not working in MongoDB
There could be many reasons why MongoDB is not working, but you must remember some procedures for sorting operations by date in MongoDB.
- Always remember that with help you are storing data in collections.
- There are two ways to store date fields in a document.
- The Date() string and ISODate() data types are used to store dates in documents.
- When you sort a date field using the sort() method, check which data type you are using.
Code example:
db.document.insertOne({ "productId" : 1001, "productDeliveryDateTime": new Date() });
{
"acknowledged" : true,
"insertedId" : ObjectId("611c9e39e1fdc428cf238802")
}
Add date using Date() string, collection name is document. You can insert date in document in the same way using ISODate().
Querying working dates using ISODate() in MongoDB
Date query using ISODate in MongoDB using $gte operator and ISODate() Let us make a collection using this document to understand the concept better.
Following is the query to construct a collection using documents.
Query:
> db.dateDemo.insertOne({"StudentName":"John","StudentAge":26,"AdmissionDate":new ISODate("2013-06-07")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a65799064dcd4a68b70ea")
}
find()
The function displays all documents in a collection.
ask:
db.dateDemo.find().pretty();
Output:
This is a date query using ISODate() in MongoDB.
Query:
> db.dateDemo.find({"AdmissionDate":{"$gte": ISODate("2013-06-07T00:00:00Z")}}).pretty();
Output:
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
$unset operator in MongoDB
Publish Date:2025/04/27 Views:77 Category:MongoDB
-
This article will discuss how the $unset operator works in MongoDB. Additionally, we will demonstrate the use of this operator to remove a field from all documents in a MongoDB collection. $unset operator in MongoDB $unset is an operator us
Compass Filters in MongoDB
Publish Date:2025/04/27 Views:132 Category:MongoDB
-
This short article will cover the various ways to use Compass filters in MongoDB . Compass Filters in MongoDB MongoDB has a GUI called Compass . It is also known as MongoDB GUI. Users can use MongoDB to inspect the contents of their stored
Sorting by timestamp in MongoDB
Publish Date:2025/04/27 Views:54 Category:MongoDB
-
This article will introduce various methods of sorting timestamps in MongoDB. Sorting by timestamp in MongoDB sort() The method will sort documents in MongoDB. The method accepts a document containing a list of fields and the order in which
Deleting a user from a database in MongoDB
Publish Date:2025/04/27 Views:50 Category:MongoDB
-
This article will explain how to delete a user from a MongoDB database. In addition, we will see an example to make the topic easier to understand. Deleting a User from a MongoDB Database Sometimes we need to remove a particular user from t
Deleting items by ID in MongoDB
Publish Date:2025/04/27 Views:158 Category:MongoDB
-
Sometimes we need to delete data from a database based on specified criteria. Unlike other SQL databases, MongoDB does not include SQL queries for this purpose. Instead, it uses commands. This article will discuss how to delete documents ba
$ne operator in MongoDB
Publish Date:2025/04/11 Views:84 Category:MongoDB
-
This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val
MongoDB $Set Operator
Publish Date:2025/04/11 Views:159 Category:MongoDB
-
With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given
Difference between $push and $addToSet in MongoDB
Publish Date:2025/04/11 Views:63 Category:MongoDB
-
This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato
Sort a collection by date in MongoDB
Publish Date:2025/04/11 Views:64 Category:MongoDB
-
In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB