javascriptstringmongodbstring-to-datetime

mongo db: use $gte & $lte to find string dates by inputing only years


I have an object that looks like this:

name:"Aachen"
mass:"21"
year:"1880-01-01T00:00:00.000"

I am trying to use $gte and $lte to find the entries that happened between certain YEARS.

I have tried this: db.collectionName.find({$expr: {$and: [{"year": {$gte:"1880"}}, {"year": {$lte: "1900"}} ]}})

but not getting any results

I think i need to parse the date to ISODate first and then destructure the year but not really sure how to perform the query.

Any guidance?

Thanks a lot


Solution

  • You cannot just query the year from a string. You have to transform the field to date and get the year from it. I would suggest using the aggregation framework for this as follows:

    db.collectionName.aggregate([
        {
            $addFields: {
                justYear: {
                    $year: {
                        $dateFromString: {
                            dateString: '$year',
                        },
                    },
                },
            },
        },
        {
            $match: {
                justYear: {
                    $gte: 1880,
                    $lte: 1900,
                },
            },
        },
    ]);
    

    Anything else let me know