I want to group all the data with startDate>=today-3 or <=today+3. Here is the database:
"startDate": {
"$date": "2024-03-05T00:00:00Z" }
Here is the query:
const dailyPlans = await DailyPlan.aggregate([
{
$match: {
_id: { $in: allPlansID },
startDate: {
$gte: startUtcDate,
$lte: endUtcDate,
},
},
},
{
$group: {
_id: {
$dateToString: {
format: "%Y-%m-%d",
date: {
$toDate: "$startDate",
},
},
},
count: { $sum: 1 },
},
},
]);
2
Answers
This is how your $group stage should look like:
(here is the correct syntaxt)
In your aggregate query, you’re using
$toDate
to convert thestartDate
field to a date object. However, it seems unnecessary becausestartDate
is already stored as a date object I assume based on yourDailyPlan.find(query)
in the commentsYour criteria looks like a
$and
criteria to me. You can leave all the date processing to$dateAdd
/$dateSubtract
.$dateTrunc
can be used to make$$NOW
, which refers to current datetime, to date only.Mongo Playground