Get documents from specific month and specific year in MongoDB

Viewed 426

I am trying to get all the documents that were created in a specific month and specific year. I save the date in "date" field so my query now looks like this:

db.collection(expenses_collection).find({
  $expr: { $eq: [{ $month: "$date" }, 3], $eq: [{ $year: "$date" }, 2020] }
});

But this query is returning me all documents which were created in 2020 and ignores month. How can I fix this issue?

Thank you in advance!

1 Answers

You should be using $and operator to bind two conditions, Otherwise it would be considering the last condition in the query. So try below one :

db.collection.find({
  $expr: {
    $and: [
      {
        "$eq": [
          {
            "$month": "$date"
          },
          3
        ]
      },
      {
        "$eq": [
          {
            "$year": "$date"
          },
          2020
        ]
      }
    ]
  }
})

Test : MongoDB-Playground

Related