在MongoDB的Query中使用$ concat $ regex

问题描述 投票:2回答:1

我试图根据用户的名字搜索用户。我的用户架构如下所示:

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

我可以运行以下查询:

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

但是我试图运行这样的查询:

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

但MongoDB不支持此功能。

有没有办法使用$regex$concat

mongodb mongoose
1个回答
4
投票

攻击表达式不支持regex表达式查询表达式。

尝试聚合

在聚合管道中创建一个额外的字段名称,其中包含名字和姓氏,然后匹配正则表达式。

const userDocs = await UserModel.aggregate
({$addFields:{
   name:{
    $concat:[
     '$firstName',
     ' ',
     '$lastName',
    ]
  }
}},
{$match:{
   name:new RegExp(`^${text}`, 'i')
}});
© www.soinside.com 2019 - 2024. All rights reserved.