This is my mongo-DB database collection image [1]: https://i.stack.imgur.com/TIKh1.png
I want to add query in which I need to get group by month and sum of (amount) from (project) array that is being embedded in (usermodel) collection
This is how i am currently doing it, but in console no output is showing
router.get('/calculatedata', Authenticate, async (req, res) => {
try {
const getUser = await UserModel.findById({ _id: req.userID });
const getProject = await getUser.aggregate([
{$unwind: '$project' },
{$group: { _id: { month: "$month" },
total:{$sum:"$project.amount"}
}
}]);
console.log(getProject)
} catch (error) {
res.status(400).send({ message: "Something Went Wrong" })
}
})
You need to extract the month from date and extract the date from string first , example:
month: {$month: { $dateFromString:{ dateString:"$project.date" , timezone:'America/New_York' }} }
or extract the month like number ( 01..12) from the string:
month: { $substr: ["$project.date", 5, 7] }