Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$regex with $concat in Query in MongoDB

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?

like image 587
carloabelli Avatar asked Sep 13 '25 01:09

carloabelli


1 Answers

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')
}});
like image 177
s7vr Avatar answered Sep 15 '25 17:09

s7vr