Aggregation - Can I match the same field multiple times?

Hello everyone, currently I am trying around with aggregation. Surely I will join the aggregation course, but I have to fullfill my exercise first. I have build a webshop and want to get the income out of my orders-collection. I matched the field createdAt with month and that is working. But I want to get the income of the day and the full year either. Now I am getting the error:

MongoServerError: Invalid $project :: caused by :: Unknown expression $day

Code:

orderRouter.get('/income', verifyTokenAndAdmin, async (req:Request, res:Response)=>{
    const date = new Date();
    const lastDay = new Date(date.setDate(date.getDate()-1));
    const year = new Date().getFullYear();
    const lastMonth = new Date(date.setMonth(date.getMonth()-1));
    const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth()-1));
    try{
        const income = await Order.aggregate([
            {$match:{createdAt:{$gte: previousMonth}}},
            {$match:{createdAt:{$gte: lastDay}}},
            {$match:{createdAt:{$eq:year}}},
            {$project: {
                month: {$month: "$createdAt"},
                day:{$day:"$createdAt"},
                year:{$year:"$createdAt"},
                sales: "$netto",
            }},
            {$group:{
                _id: {
                    "month":"$month",
                    "day":"$day",
                    "year":"$year",
            },
                total:{$sum: "$sales"}
            }}
           
        ]);
        console.log(income);

Thanks for your help

You should do it before producing any production code.

Yes you may match the same field multiple times. Look at $and to see how to.

The following

tells you that

is wrong. And if you google for mongodb $day, the first result will be

which is closer to what you need.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.