How to use $lt and $gte Operator In Mongoose
The $gte operator matches documents where the value of a field is greater than or equal to a specified value, while the $lt operator matches documents where the value of a field is less than a specified value.
Let’s Find all patients with appointments scheduled for January 23, 2024, and exclude the _id field from the results.
db.patients.find({appointment: {$gte: new ISODate("2024-01-23"), $lt: new ISODate("2024-01-24")}}, {_id: 0})
Output:
Explanation: The condition, greater than or equal to 2024-01-23 and less than 2024-01-24, simply translates to all the documents with date value 2024-01-23.
How to Query Documents at a Specific Date in Mongoose?How to Query Documents at a Specific Date in Mongoose?
In MongoDB/Mongoose, querying for data at a specific date is a common requirement. Whether we are looking to retrieve data for a specific day, month, or year, understanding how to query at a specific date is essential.
In this article, We will learn about How to Query Documents at a Specific Date in Mongoose by understanding various methods along with the implementation.
How to Query Documents at a Specific Date in Mongoose?
When working with MongoDB/Mongoose, we need to retrieve data based on specific dates. MongoDB uses the ISODate format to store dates, which allows for precise querying. Below are the methods that help to query documents at a specific date in Mongoose are as follows:
Let’s set up an Environment:
To understand How to Query Documents at a Specific Date in Mongoose we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called patients which contains information like name, appointment of the patients in various documents.
db.patients.insertMany([
{ name: 'Aayush', appointment: new ISODate("2024-05-10") },
{ name: 'Akash', appointment: new ISODate("2024-06-12") },
{ name: 'Dhruv', appointment: new ISODate("2023-12-25") },
{ name: 'Diksha', appointment: new ISODate("2025-10-01") },
{ name: 'Aadarsh', appointment: new ISODate("2024-01-23") },
{ name: 'Shivam', appointment: new ISODate("2024-12-15") },
{ name: 'Satyam', appointment: new ISODate("2024-01-23") }
]);
Using the following query, we can see the current documents in the patients collection
db.patients.find({}, {_id: 0}).pretty()
Output:
Now that we have the setup in place, we will look at several method for querying at a specific date in MongoDB