Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: find by specific month

I have this model on my db:

{
    "title" : {
        type: String
    }
    , "date" : {
        type: Date
        , default: Date.now
    }
}

A document sample is:

{
     "_id": "5aa2d0f9e10fed2054fe1138",
     "title": "Hello World",
     "date": "2018-03-09T03:00:00.000Z"
}

And I just want to get all documents which date has an specific month, i.e.: 3, which means March. It really doesn't matter of what day/year.

I've found some aggregations answers but in all of them I had to create a date with a minimum year to add to $gte, but I don't wanna do this.

Is there another way?

MongoDB version: 3.4.7

Thanks.

like image 422
nncl Avatar asked Dec 24 '22 08:12

nncl


1 Answers

Hope this will solve it. I am also wondering how to use $month in match stage itself. I will consider this as a partial answer.

V3.6

db.test.aggregate([
      {$addFields: {  "month" : {$month: '$date'}}},
      {$match: { month: 3}}
    ]);

V3.4

db.test.aggregate([
  {$project: { title:1, date:1, "month" : {$month: '$date'}}},
  {$match: { month: 3}}
]);
like image 87
Krishna Avatar answered Jan 11 '23 00:01

Krishna