
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 Data for Specific Date in MongoDB
Let’s say you have saved the Login date of users. Now, you want the count of records for specific date only i.e. login date. For this, use $gte and $lt operator along with count(). Let us first create a collection with documents −
> db.findDataByDateDemo.insertOne({"UserName":"John","UserLoginDate":new ISODate("2019-01-31")}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd8cd7bf3115999ed511ed") } > db.findDataByDateDemo.insertOne({"UserName":"Larry","UserLoginDate":new ISODate("2019-02-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd8ce7bf3115999ed511ee") } > db.findDataByDateDemo.insertOne({"UserName":"Sam","UserLoginDate":new ISODate("2019-05-02")}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd8cf3bf3115999ed511ef") } > db.findDataByDateDemo.insertOne({"UserName":"David","UserLoginDate":new ISODate("2019-05-16")}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd8d00bf3115999ed511f0") } > db.findDataByDateDemo.insertOne({"UserName":"Carol","UserLoginDate":new ISODate("2019-10-19")}); { "acknowledged" : true, "insertedId" : ObjectId("5cdd8d0ebf3115999ed511f1") }
Following is the query to display all documents from a collection with the help of find() method −
> db.findDataByDateDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdd8cd7bf3115999ed511ed"), "UserName" : "John", "UserLoginDate" : ISODate("2019-01-31T00:00:00Z") } { "_id" : ObjectId("5cdd8ce7bf3115999ed511ee"), "UserName" : "Larry", "UserLoginDate" : ISODate("2019-02-01T00:00:00Z") } { "_id" : ObjectId("5cdd8cf3bf3115999ed511ef"), "UserName" : "Sam", "UserLoginDate" : ISODate("2019-05-02T00:00:00Z") } { "_id" : ObjectId("5cdd8d00bf3115999ed511f0"), "UserName" : "David", "UserLoginDate" : ISODate("2019-05-16T00:00:00Z") } { "_id" : ObjectId("5cdd8d0ebf3115999ed511f1"), "UserName" : "Carol", "UserLoginDate" : ISODate("2019-10-19T00:00:00Z") }
Following is the query to find data for a specific date in MongoDB. Here, we are getting the users who logged in between specific dates −
> db.findDataByDateDemo.count({"UserLoginDate":{ "$gte": new Date("2019-05-02"), "$lt": new Date("2019-05-18") }});
This will produce the following output −
2
Advertisements