Return query based on date in MongoDB?

MongoDBDatabaseBig Data Analytics

To return query based on the date in MongoDB, let us take an example.

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.returnQueryFromDate.insertOne({"PassengerName":"John","PassengerAge":23,"PassengerArrivalTime":new ISODate("2018-03-10 14:45:56")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a57be9064dcd4a68b70e4")
}
> db.returnQueryFromDate.insertOne({"PassengerName":"Larry","PassengerAge":21,"PassengerArrivalTime":new ISODate("2018-05-19 11:10:23")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e5")
}
> db.returnQueryFromDate.insertOne({"PassengerName":"Mike","PassengerAge":24,"PassengerArrivalTime":new ISODate("2018-08-25 16:40:12")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e6")
}
>db.returnQueryFromDate.insertOne({"PassengerName":"Carol","PassengerAge":26,"PassengerArrivalTime":new ISODate("2019-01-29 09:45:10")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e7")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c8a57be9064dcd4a68b70e4"),
   "PassengerName" : "John",
   "PassengerAge" : 23,
   "PassengerArrivalTime" : ISODate("2018-03-10T14:45:56Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e5"),
   "PassengerName" : "Larry",
   "PassengerAge" : 21,
   "PassengerArrivalTime" : ISODate("2018-05-19T11:10:23Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e6"),
   "PassengerName" : "Mike",
   "PassengerAge" : 24,
   "PassengerArrivalTime" : ISODate("2018-08-25T16:40:12Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e7"),
   "PassengerName" : "Carol",
   "PassengerAge" : 26,
   "PassengerArrivalTime" : ISODate("2019-01-29T09:45:10Z")
}

Here is return query based on date. The records with a date greater than 2018-05-19T11:10:23Z will be displayed −

> db.returnQueryFromDate.find({"PassengerArrivalTime" : { $gte : new ISODate("2018-05-19T11:10:23Z") }}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e5"),
   "PassengerName" : "Larry",
   "PassengerAge" : 21,
   "PassengerArrivalTime" : ISODate("2018-05-19T11:10:23Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e6"),
   "PassengerName" : "Mike",
   "PassengerAge" : 24,
   "PassengerArrivalTime" : ISODate("2018-08-25T16:40:12Z")
}
{
   "_id" : ObjectId("5c8a57bf9064dcd4a68b70e7"),
   "PassengerName" : "Carol",
   "PassengerAge" : 26,
   "PassengerArrivalTime" : ISODate("2019-01-29T09:45:10Z")
}
raja
Published on 29-Mar-2019 10:02:58
Advertisements