- 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
MongoDB query to get date records in a range
To get date records in a range, use $gt along with $lt. Let us create a collection with documents −
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-11 12:30:10")}); { "acknowledged" : true, "insertedId" : ObjectId("5e2863fecfb11e5c34d89927") } > db.demo60.insertOne({"ArrivalDate":new ISODate("2019-10-12 03:10:00")}); { "acknowledged" : true, "insertedId" : ObjectId("5e28641acfb11e5c34d89928") } > db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-14 05:11:20")}); { "acknowledged" : true, "insertedId" : ObjectId("5e28642acfb11e5c34d89929") }
Display all documents from a collection with the help of find() method −
> db.demo60.find();
This will produce the following output −
{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") } { "_id" : ObjectId("5e28641acfb11e5c34d89928"), "ArrivalDate" : ISODate("2019-10-12T03:10:00Z") } { "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }
Following is the query to get date records in a range −
> db.demo60.find({"ArrivalDate": {"$gt":ISODate("2019-01-09T12:30:10Z"), "$lt": ISODate("2019-01-16T12:30:10Z")}});
This will produce the following output −
{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") } { "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }
Advertisements