Get documents expired before today in MongoDB?


You can use $lte operator along with Date() for this. Let us first create a collection with documents. Here, we have set the date 2019-05-11, which is the current date −

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

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

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

This will produce the following output −

{
   "_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")
}

Following is the query to get documents expired before today in MongoDB −

> db.getDocumentsExpiredDemo.find({ "ArrivalDate": { $lte : new Date()}});

This will produce the following output −

{ "_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") }

Updated on: 30-Jul-2019

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements