![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to search date between two dates in MongoDB?
To search date between two dates in MongoDB, use $gte and $lt. Let us create a collection with documents −
> db.demo524.insertOne({"EndDate":new ISODate("2020-01-19")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8adbe5437efc8605595b63") } > db.demo524.insertOne({"EndDate":new ISODate("2020-01-20")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8adbec437efc8605595b64") } > db.demo524.insertOne({"EndDate":new ISODate("2020-12-31")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8adbf3437efc8605595b65") }
Display all documents from a collection with the help of find() method −
> db.demo524.find();
This will produce the following output −
{ "_id" : ObjectId("5e8adbe5437efc8605595b63"), "EndDate" : ISODate("2020-01-19T00:00:00Z") } { "_id" : ObjectId("5e8adbec437efc8605595b64"), "EndDate" : ISODate("2020-01-20T00:00:00Z") } { "_id" : ObjectId("5e8adbf3437efc8605595b65"), "EndDate" : ISODate("2020-12-31T00:00:00Z") }
Following is the query to search data between two dates in MongoDB −
> var first = new ISODate("2020-01-04"); > var last = new ISODate("2020-01-31"); > db.demo524.find({EndDate: {$gte: first, $lt: last}});
This will produce the following output −
{ "_id" : ObjectId("5e8adbe5437efc8605595b63"), "EndDate" : ISODate("2020-01-19T00:00:00Z") } { "_id" : ObjectId("5e8adbec437efc8605595b64"), "EndDate" : ISODate("2020-01-20T00:00:00Z") }
Advertisements