![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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") }
Advertisements