skip to Main Content

i have collection vacation that looks like something like this :

[
  {
  _id: ..
  employeeId: ...
  type: ...
  startDate:2022-09-10T00:00:00.000+00:00
  endDate: 2022-09-15T00:00:00.000+00:00
  }
  {
  _id: ..
  employeeId: ...
  type: ...
  startDate:2022-01-10T00:00:00.000+00:00
  endDate: 2022-02-15T00:00:00.000+00:00
  }
  {
  _id: ..
  employeeId: ...
  type: ...
  startDate:2022-03-10T00:00:00.000+00:00
  endDate: 2022-04-15T00:00:00.000+00:00
  }
]
...

i want to get docs only when the month in startDate is equal to specific month


const Vacation = require("../models/Vacation");

const vacations = await Vacation.find({// where month in startDate is equal to 2})


how can i perform such query ? thanks in advance

2

Answers


  1. You can write an aggregation query like this:

    const vacations = await Vacation.aggregate(
     [
      {
        "$match": {
          $expr: {
            "$eq": [
              {
                "$month": {
                  "$dateFromString": {
                    "dateString": "$startDate",
                  }
                }
              },
              3
            ]
          }
        }
      },
     ]
    );
    

    Here we, construct a date object from a string using $dateFromString operator, and then find the month value using $month. Then we perform an equality comparison, using $eq. Read more about aggregation operations on MongoDB here. See the above query working here.

    Login or Signup to reply.
  2. As mentioned in my comment, you don’t need $dateFromString when date values are stored correctly:

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            "$eq": [{ "$month": "$startDate" }, 3 ]
          }
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search