Query MongoDB for a datetime value less than NOW?

To query MongoDB for datetime values less than the current time, use the $lte operator with new Date() which returns the current timestamp.

Syntax

db.collection.find({
    "dateField": { $lte: new Date() }
});

Sample Data

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

Query Documents with Dates Less Than NOW

Find all documents where ArrivalDate is less than or equal to the current date ?

db.dateTimeValueLessThanNowDemo.find({
    "ArrivalDate": { $lte: new Date() }
}).pretty();
{
    "_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")
}

Key Points

  • new Date() returns the current timestamp when the query executes
  • $lte includes documents with dates equal to the current time
  • Use $lt instead of $lte to exclude the current timestamp
  • All dates are stored as UTC in MongoDB

Conclusion

The $lte operator combined with new Date() effectively filters documents based on current time. This approach is useful for finding expired records or historical data in real-time applications.

Updated on: 2026-03-15T00:41:43+05:30

758 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements