MongoDB query to get date records in a range

MongoDBDatabaseBig Data Analytics

To get date records in a range, use $gt along with $lt. Let us create a collection with documents −

> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-11 12:30:10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2863fecfb11e5c34d89927")
}
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-10-12 03:10:00")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28641acfb11e5c34d89928")
}
> db.demo60.insertOne({"ArrivalDate":new ISODate("2019-01-14 05:11:20")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e28642acfb11e5c34d89929")
}

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

> db.demo60.find();

This will produce the following output −

{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") }
{ "_id" : ObjectId("5e28641acfb11e5c34d89928"), "ArrivalDate" : ISODate("2019-10-12T03:10:00Z") }
{ "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }

Following is the query to get date records in a range −

> db.demo60.find({"ArrivalDate": {"$gt":ISODate("2019-01-09T12:30:10Z"), "$lt": ISODate("2019-01-16T12:30:10Z")}});

This will produce the following output −

{ "_id" : ObjectId("5e2863fecfb11e5c34d89927"), "ArrivalDate" : ISODate("2019-01-11T12:30:10Z") }
{ "_id" : ObjectId("5e28642acfb11e5c34d89929"), "ArrivalDate" : ISODate("2019-01-14T05:11:20Z") }
raja
Published on 03-Apr-2020 16:13:01
Advertisements