How to match date with MongoDB $match?

MongoDBDatabaseBig Data Analytics

To match date, use $match along with aggregate(). Let us create a collection with documents −

> db.demo491.insertOne({"ShippingDate":new ISODate("2020-01-10")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a09b0f3fa88e22790be")
}
> db.demo491.insertOne({"ShippingDate":new ISODate("2020-02-21")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a0eb0f3fa88e22790bf")
}
> db.demo491.insertOne({"ShippingDate":new ISODate("2020-03-23")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a1db0f3fa88e22790c0")
}
> db.demo491.insertOne({"ShippingDate":new ISODate()});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e849a28b0f3fa88e22790c1")
}

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

> db.demo491.find();

This will produce the following output −

{ "_id" : ObjectId("5e849a09b0f3fa88e22790be"), "ShippingDate" : ISODate("2020-01-
10T00:00:00Z") }
{ "_id" : ObjectId("5e849a0eb0f3fa88e22790bf"), "ShippingDate" : ISODate("2020-02-
21T00:00:00Z") }
{ "_id" : ObjectId("5e849a1db0f3fa88e22790c0"), "ShippingDate" : ISODate("2020-03-
23T00:00:00Z") }
{ "_id" : ObjectId("5e849a28b0f3fa88e22790c1"), "ShippingDate" : ISODate("2020-04-
01T13:42:00.090Z") }

Following is the query to match date with $match using MongoDB −

> db.demo491.aggregate([
... {
...    '$match' : { 'ShippingDate' : { '$gte' : ISODate('2020-02-24T18:10:11.000Z') } }
... }
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e849a1db0f3fa88e22790c0"), "ShippingDate" : ISODate("2020-03-
23T00:00:00Z") }
{ "_id" : ObjectId("5e849a28b0f3fa88e22790c1"), "ShippingDate" : ISODate("2020-04-
01T13:42:00.090Z") }
raja
Published on 13-May-2020 08:54:56
Advertisements