Query MongoDB for a datetime value less than NOW?


You can use $lte operator along with new Date() for this. Let us first create a collection with documents

>db.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Larry","CustomerProductName":"Product-1","ArrivalDate":new ISODate("2017-01-31")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e8ab66324ffac2a7dc59")
}
>db.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Mike","CustomerProductName":"Product-2","ArrivalDate":new ISODate("2019-04-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e8c166324ffac2a7dc5a")
}
>db.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Chris","CustomerProductName":"Product-3","ArrivalDate":new ISODate("2019-03-31")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e8d266324ffac2a7dc5b")
}
>db.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Robert","CustomerProductName":"Product-4","ArrivalDate":new ISODate("2019-04-02")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca1e8e766324ffac2a7dc5c")
}

Following is the query to display all documents from a collection with the help of find() method

> db.dateTimeValueLessThanNowDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca1e8c166324ffac2a7dc5a"),
   "CustomerName" : "Mike",
   "CustomerProductName" : "Product-2",
   "ArrivalDate" : ISODate("2019-04-01T00:00:00Z")
}
{
   "_id" : ObjectId("5ca1e8d266324ffac2a7dc5b"),
   "CustomerName" : "Chris",
   "CustomerProductName" : "Product-3",
   "ArrivalDate" : ISODate("2019-03-31T00:00:00Z")
}
{
   "_id" : ObjectId("5ca1e8e766324ffac2a7dc5c"),
   "CustomerName" : "Robert",
   "CustomerProductName" : "Product-4",
   "ArrivalDate" : ISODate("2019-04-02T00:00:00Z")
}

Following is the query for datetime value less than NOW. Let’s say the current date is 2019-04-02

> db.dateTimeValueLessThanNowDemo.find({ ArrivalDate: { $lte: new Date() } }).pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca1e8ab66324ffac2a7dc59"),
   "CustomerName" : "Larry",
   "CustomerProductName" : "Product-1",
   "ArrivalDate" : ISODate("2017-01-31T00:00:00Z")
}
{
   "_id" : ObjectId("5ca1e8c166324ffac2a7dc5a"),
   "CustomerName" : "Mike",
   "CustomerProductName" : "Product-2",
   "ArrivalDate" : ISODate("2019-04-01T00:00:00Z")
}
{
   "_id" : ObjectId("5ca1e8d266324ffac2a7dc5b"),
   "CustomerName" : "Chris",
   "CustomerProductName" : "Product-3",
   "ArrivalDate" : ISODate("2019-03-31T00:00:00Z")
}

Updated on: 30-Jul-2019

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements