Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Matching with $month

Hello !

I’m trying to do a really simple thing but I don’t know why it’s not working.

I have this aggregate

$addFields
{
    "month_document": {"$month": "$date_document"},
    "month_date": {"$month": new Date()}
}

Which gives the following result :
month_document = 6
month_date = 6

Then I’m trying to match all my documents with month_date.

$match
{
    "month_document": "$month_date"
}

And it doesn’t work but "month_document": 6 works fine.

I can’t figure it out why ?

EDIT :

I tried to convert my date to string

addFields
{
    "month_document": { $dateToString: { format: "%m-%Y", date: "$date_document" } },
    "month_date": { $dateToString: { format: "%m-%Y", date: new Date() } },
}

Which gives the following result :
month_document = 06-2020
month_date = 06-2020

And it’s not working either but matching month_document with the literal string “06-2020” works.

Because, you cannot use the $month_date in the $match stage. The $match stage uses MongoDB Query Language operators (those you use with the find method) for comparison. You can match two document / derived variables using the aggreagtion operators only. To use aggregation operators you must use them with the $expr operator as shown below:

db.test.aggregate( [
  { 
      $addFields: {
          month_document: { "$month": "$date_document" },
          month_date: {"$month": new Date() } 
      }
  },
  { 
      $match: { $expr: { $eq: [ "$month_document", "$month_date" ] } }
  }
] )

Or, simply (this is same as the above aggregation):

db.test.aggregate( [
  { 
      $match: { $expr: { $eq: [ { "$month": "$date" }, { "$month": new Date() } ] } }
  }
] )

The same is the issue with the “date to string” converted value fields.

Also, note that when using the month-year format string date for comparison, you should be using the yyyy-mm format (not the mm-yyyy format).

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.