Dipesh Lohani
Dipesh Lohani

Reputation: 356

Compare string date in mongoose with Date.now() or new Date()

I have a string date saved in MongoDB as such: '19 Dec 2019'. I want to get all the matching date with new Date() i.e current date.

Mongo stored Date:

db_date: '18 Dec 2019'

. Match this date with current date,we get this using

current_date: new Date();

and return an array of matches.

Model.find() ???

Upvotes: 1

Views: 1611

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Please try this :

db.yourCollectionName.aggregate([{
    $addFields: {
        /** converting month from string to num :: Dec to 12 & extracting date & year from string */
        month: {
            $indexOfArray: [[, "Jan", "Feb", "Mar", "Aprl", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
                , { $arrayElemAt: [{ $split: ['$db_date', " "] }, 1] }]
        }
        , date: { $toInt: { $arrayElemAt: [{ $split: ['$db_date', " "] }, 0] } }, year: { $toInt: { $arrayElemAt: [{ $split: ['$db_date', " "] }, 2] } }
    }
}, {
    /** db_date is being converted to format ISODate() from parts year + month + day & then to this : "2019-12-18" */
    $addFields: {
        db_date: {
            $dateToString: {
                format: "%Y-%m-%d", date: {
                    $dateFromParts: {
                        'year': '$year', 'month': '$month', 'day': '$date'
                    }
                }
            }
        }
    }
}, { $project: { 'month': 0, 'year': 0, 'date': 0 } },
{
    /** Here we're converting ISODate() from input to like this : "2019-12-19", This is what you actually asked for */
    $match: {
        $expr: {
            $eq: ['$db_date', {
                $dateToString: {
                    format: "%Y-%m-%d", date: new Date()
                }
            }]
        }
    }
}
])

This query should help you to get required results, but in my opinion it's a hefty task to do this kind of conversions, You can usually overcome this by thinking thru your transactions at the time of DB design & then by storing data in DB as per your read requirements, if not - in the other way maybe ease your DB by converting the input in your code to match with data stored in DB !!

Upvotes: 1

Related Questions