Syntax error Find posts that are older than current date in MongoDB?

Find posts that are older than current date in MongoDB?



To find posts older than current date in MongoDB, use $lte. Let us create a collection with documents −

> db.demo746.insertOne({DueDate:new Date("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae67eca930c785c834e55b")
}
> db.demo746.insertOne({DueDate:new Date("2020-10-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae67eda930c785c834e55c")
}
> db.demo746.insertOne({DueDate:new Date("2020-03-05")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae67eea930c785c834e55d")
}
> db.demo746.insertOne({DueDate:new Date("2020-05-04")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae67f1a930c785c834e55e")
}

Display all documents from a collection with the help of find() method −

> db.demo746.find();

This will produce the following output −

{ "_id" : ObjectId("5eae67eca930c785c834e55b"), "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5eae67eda930c785c834e55c"), "DueDate" : ISODate("2020-10-10T00:00:00Z") }
{ "_id" : ObjectId("5eae67eea930c785c834e55d"), "DueDate" : ISODate("2020-03-05T00:00:00Z") }
{ "_id" : ObjectId("5eae67f1a930c785c834e55e"), "DueDate" : ISODate("2020-05-04T00:00:00Z") }

Following is the query to find posts older than the current date −

> db.demo746.find({DueDate:{$lte:new Date()}});

This will produce the following output −

"_id" : ObjectId("5eae67eca930c785c834e55b"), "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5eae67eea930c785c834e55d"), "DueDate" : ISODate("2020-03-05T00:00:00Z") }
Updated on: 2020-06-30T08:06:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements