2023-08-31

MongoDB - Extract the first year of a string, using RegEx

 db.collection.aggregate([

    {$addFields: {

        "year": {$regexFindAll: {

            input: "$born_string", 

            regex: /\b\d{4}\b/

        }},

    }},

    {$addFields: {

        "year": {$arrayElemAt: ["$year",0]},

    }},

    {$addFields: {

        "year": "$year.match",

    }},

    {$addFields: {

        "year": {$toInt: "$year"},

    }},

]);


No comments:

Post a Comment