
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Objects Between Two Dates in MongoDB
Use operator $gte and $lt to find objects between two dates in MongoDB. To understand these operators, let us create a collection.
Creating a collection here:
>db.order.insert({"OrderId":1,"OrderAddrees":"US","OrderDateTime":ISODate("2019-02-19")}; WriteResult({ "nInserted" : 1 }) >db.order.insert({"OrderId":2,"OrderAddrees":"UK","OrderDateTime":ISODate("2019-02-26")}; WriteResult({ "nInserted" : 1 })
Display all documents from the collection with the help of find() method. The query is as follows:
> db.order.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6c072068174aae23f5ef57"), "OrderId" : 1, "OrderAddrees" : "US", "OrderDateTime" : ISODate("2019-02-19T00:00:00Z") } { "_id" : ObjectId("5c6c073568174aae23f5ef58"), "OrderId" : 2, "OrderAddrees" : "UK", "OrderDateTime" : ISODate("2019-02-26T00:00:00Z") }
Here is the query to find objects between two dates:
> db.order.find({"OrderDateTime":{ $gte:ISODate("2019-02-10"), $lt:ISODate("2019-02-21") } }).pretty();
The following is the output:
{ "_id" : ObjectId("5c6c072068174aae23f5ef57"), "OrderId" : 1, "OrderAddrees" : "US", "OrderDateTime" : ISODate("2019-02-19T00:00:00Z") }
Advertisements