Syntax error MongoDB query to search for Month and Day only?

MongoDB query to search for Month and Day only?



To search for month and day only, use the aggregate framework.

Let us first create a collection with documents −

> db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2019-04-27")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefbcaeef71edecf6a1f6b2")
}
> db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2018-04-30")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefbcb7ef71edecf6a1f6b3")
}
> db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2018-04-27")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefbcbcef71edecf6a1f6b4")
}
> db.monthAndDayDemo.insertOne({"LoginDate":new ISODate("2016-04-27")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefbdaaef71edecf6a1f6b5")
}

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

> db.monthAndDayDemo.find();

Output

{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "LoginDate" : ISODate("2019-04-27T00:00:00Z") }
{ "_id" : ObjectId("5cefbcb7ef71edecf6a1f6b3"), "LoginDate" : ISODate("2018-04-30T00:00:00Z") }
{ "_id" : ObjectId("5cefbcbcef71edecf6a1f6b4"), "LoginDate" : ISODate("2018-04-27T00:00:00Z") }
{ "_id" : ObjectId("5cefbdaaef71edecf6a1f6b5"), "LoginDate" : ISODate("2016-04-27T00:00:00Z") }

Following is the query to search for month and day only −

{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "LoginDate" : ISODate("2019-04-27T00:00:00Z") }
> db.monthAndDayDemo.aggregate( { "$project": { "m":{"$month":"$LoginDate"}, 
"d": { "$dayOfMonth":"$LoginDate" } }}, { "$match":{ "m": 4, "d": 27 } } );

Output

{ "_id" : ObjectId("5cefbcaeef71edecf6a1f6b2"), "m" : 4, "d" : 27 }
{ "_id" : ObjectId("5cefbcbcef71edecf6a1f6b4"), "m" : 4, "d" : 27 }
{ "_id" : ObjectId("5cefbdaaef71edecf6a1f6b5"), "m" : 4, "d" : 27 }
Updated on: 2019-07-30T22:30:26+05:30

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements