MongoDB query to search date records using only Month and Day

MongoDBDatabaseBig Data Analytics

To search using month and day only, use $where. Let us create a collection with documents −

> db.demo181.insertOne({"ShippingDate":new ISODate("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e398a699e4f06af551997fe")
}
> db.demo181.insertOne({"ShippingDate":new ISODate("2019-12-11")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e398a729e4f06af551997ff")
}
> db.demo181.insertOne({"ShippingDate":new ISODate("2018-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e398a7d9e4f06af55199800")
}
> db.demo181.insertOne({"ShippingDate":new ISODate("2020-10-12")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e398a879e4f06af55199801")
}

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

> db.demo181.find();

This will produce the following output −

{ "_id" : ObjectId("5e398a699e4f06af551997fe"), "ShippingDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e398a729e4f06af551997ff"), "ShippingDate" : ISODate("2019-12-11T00:00:00Z") }
{ "_id" : ObjectId("5e398a7d9e4f06af55199800"), "ShippingDate" : ISODate("2018-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e398a879e4f06af55199801"), "ShippingDate" : ISODate("2020-10-12T00:00:00Z") }

Following is the query to search with Month and Day −

> db.demo181.find({$where : function() { return this.ShippingDate.getMonth() == 1 || this.ShippingDate.getDate() == 10} })

This will produce the following output −

{ "_id" : ObjectId("5e398a699e4f06af551997fe"), "ShippingDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e398a7d9e4f06af55199800"), "ShippingDate" : ISODate("2018-01-10T00:00:00Z") }
raja
Published on 27-Mar-2020 12:24:59
Advertisements