4

I am trying to search for users based on their names. My user schema looks like:

user: {
  firstName: string,
  lastName: string,
  ...
}

I can run the following query fine:

const userDocs = await UserModel
  .find({
    $expr: {
      $eq: [
        {
          $concat: [
            '$firstName',
            ' ',
            '$lastName',
          ],
        },
        'John Doe',
      ],
    },
  });

However I am trying to run a query such as this:

const userDocs = await UserModel
  .find({
    $expr: {
      $regex: [
        {
          $concat: [
            '$firstName',
            ' ',
            '$lastName',
          ],
        },
        new RegExp(`^${text}`, 'i'),
      ],
    },
  });

However MongoDB does not support this.

Is there a way to use $regex with a $concat?

2 Answers 2

10

Aggression expression don't support regex expression query expression do.

Try aggregate

Create a extra field name in the aggregation pipeline combining first name and last name followed by match with regular expression.

const userDocs = await UserModel.aggregate
({$addFields:{
   name:{
    $concat:[
     '$firstName',
     ' ',
     '$lastName',
    ]
  }
}},
{$match:{
   name:new RegExp(`^${text}`, 'i')
}});
Sign up to request clarification or add additional context in comments.

Comments

2

You can also try $regexMatch to query without aggregate like this

const userDocs = await UserModel
  .find({
    $expr: {
        $regexMatch: {
            input: {
                $concat: ['$firstName', ' ', '$lastName']
            }
            regex: /^${text}/
            options: 'i'
        }
    }
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.