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

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements