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
CodePudding user response:
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.