Search code examples
regexmongodbpipelinelookup

Unrecognized expression ‘$regex’


Not able to get desired output. Getting “Unrecognized expression ‘$regex’” error

[
    {
        '$lookup': {
            'from': 'profiles',
            'let': {
                'userId': '$userId',
            },
            'pipeline': [
                {
                    '$match': {
                        $expr: {
                            $and: [
                                { '$eq': ['$uniqueId', '$$mcontactId'] },
                                {
                                    $or: [{ 'birthDate': { '$regex': '$$today' } },
                                        { 'spouseBirthdate': { '$regex': '$$today' } },
                                        { 'weddingAnniversary': { '$regex': '$$today' } },
                                    ],
                                },
                            ],
                        },
                    },
                },
                {
                    '$project': {
                        'userId': 1,
                        'uniqueId': 1,
                        'mobileNumber': 1,
                        'whatsApp': 1,
                        'emailId': 1,
                        'lastName': 1,
                        'firstName': 1,
                        'address': 1,
                        'signature': 1,
                    },
                },
            ],
            'as': 'profile',
        },
    },
]

Solution

  • $regex is a query operator, you are trying to use it within an $expr which uses the "aggregation" language as oppose to the "query" language normally used within a $match stage.

    Apart from that you have some other issue's in your pipeline, for example you only define $userId as a variable for the $lookup stage but in it you're trying to use $$today and $$mcontactId which are not defined anywhere.

    Regardless once you sort out those issue's you have two options:

    1. if the regex match is not related to the input variables just use $regex outside the $expr, like so:
    {
        '$match': {
            $and: [
                {
                    $expr: {
                        '$eq': [
                            '$uniqueId',
                            '$$userId',
                        ],
                    },
    
                },
                {
                    $or: [
                        {
                            'birthDate': {
                                '$regex': '03-05',
                            },
                        },
                    ],
                },
            ],
        },
    },
    

    Mongo Playground

    1. if the regex does not to use an input variable from the $lookup then you need to use an aggregation operator, like $regexMatch to do the match within the $expr