3

Is there any way to compare date in MongoDb collection only with a month or year. For example:-

documents in collection:-

{
"pageName": "xyz",
"createdAt": "ISODate("2017-02-19T18:30:00Z")"
},
{
"pageName": "abc",
"createdAt": "ISODate("2017-03-19T18:30:00Z")"
},
{
"pageName": "pqr",
"createdAt": "ISODate("2018-02-19T18:30:00Z")"
},
{
"pageName": "dfg",
 "createdAt": "ISODate("2017-03-19T18:30:00Z")"
}

What i am expecting is:- If i pass only a month say 02 and year say 2017 then it will return:-

{
  "pageName": "xyz",
  "createdAt": "ISODate("2017-02-19T18:30:00Z")"
}

help me in writing MongoDb query for this scenario.

Joe
  • 141
  • 1
  • 2
  • 8

1 Answers1

2

The below query will work for you case.

db.getCollection('collection_name').aggregate(
   [
     {
       $project:
         {
           pageName: "$pageName",
           createdAt: "$createdAt",
           year: { $year: "$createdAt" },
           month: { $month: "$createdAt" }
         }
     },
     { $match : { "month" : 2, "year": 2017 } }
   ]
)
Puneet Singh
  • 3,477
  • 1
  • 26
  • 39