Syntax error MongoDB query to search date records using only Month and Day

MongoDB query to search date records using only Month and Day



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") }
Updated on: 2020-03-27T07:56:16+05:30

774 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements