Get the exact number of months between two dates in MongoDB

35 Views Asked by At

If the current date is 2/22/2023 and the second date is 3/22/2023, the difference in months should be exactly 1.00, even if the amount of days between them is 28.

I have tried to use aggregation pipes such as $dateDiff but it only returns a whole difference between the dates (not precise, as I've tried with the following two dates 2/11/2023 & 3/23/2023 and it resulted in 1 as well):


        const query = OrderModel.aggregate([
            {
                $lookup: {
                    from: "customers",
                    localField: "customer",
                    foreignField: "_id",
                    as: "customer_data",
                },
            },
            {
                $unwind: "$customer_data",
            },
            {
                $addFields: {
                    date_diff: {
                        $dateDiff: {
                            startDate: {
                                $toDate: "$start_date"
                            },
                            endDate: {
                                $toDate: currentDate.getTime()
                            },
                            unit: "month"
                        },
                    },
                    customer: "$customer_data._id",
                },
            }
        ]);

Is it possible to do it through mongo aggregation or do I have to use a node library?

0

There are 0 best solutions below