Get documents expired before today in MongoDB?

To get documents expired before today in MongoDB, use the $lte operator with new Date() to find all documents where the date field is less than or equal to the current date.

Syntax

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

Sample Data

db.getDocumentsExpiredDemo.insertMany([
    { "ArrivalDate": new ISODate("2019-05-11") },
    { "ArrivalDate": new ISODate("2019-01-01") },
    { "ArrivalDate": new ISODate("2019-05-10") },
    { "ArrivalDate": new ISODate("2019-02-01") }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd563b17924bb85b3f4893b"),
        ObjectId("5cd563bf7924bb85b3f4893c"),
        ObjectId("5cd563ca7924bb85b3f4893d"),
        ObjectId("5cd563e77924bb85b3f4893e")
    ]
}

View All Documents

db.getDocumentsExpiredDemo.find().pretty();
{
    "_id": ObjectId("5cd563b17924bb85b3f4893b"),
    "ArrivalDate": ISODate("2019-05-11T00:00:00Z")
}
{
    "_id": ObjectId("5cd563bf7924bb85b3f4893c"),
    "ArrivalDate": ISODate("2019-01-01T00:00:00Z")
}
{
    "_id": ObjectId("5cd563ca7924bb85b3f4893d"),
    "ArrivalDate": ISODate("2019-05-10T00:00:00Z")
}
{
    "_id": ObjectId("5cd563e77924bb85b3f4893e"),
    "ArrivalDate": ISODate("2019-02-01T00:00:00Z")
}

Example: Get Expired Documents

Find all documents where ArrivalDate is before today's date ?

db.getDocumentsExpiredDemo.find({ "ArrivalDate": { $lte: new Date() } });
{ "_id": ObjectId("5cd563bf7924bb85b3f4893c"), "ArrivalDate": ISODate("2019-01-01T00:00:00Z") }
{ "_id": ObjectId("5cd563ca7924bb85b3f4893d"), "ArrivalDate": ISODate("2019-05-10T00:00:00Z") }
{ "_id": ObjectId("5cd563e77924bb85b3f4893e"), "ArrivalDate": ISODate("2019-02-01T00:00:00Z") }

Key Points

  • The $lte operator finds documents where the field value is less than or equal to the specified value.
  • new Date() returns the current timestamp, making the query dynamic.
  • Documents with dates equal to today are also included in the results.

Conclusion

Use { "dateField": { $lte: new Date() } } to efficiently query for expired documents in MongoDB. The $lte operator combined with new Date() provides a dynamic way to find all documents with dates on or before the current date.

Updated on: 2026-03-15T01:13:42+05:30

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements