首页 > 解决方案 > mongodb部分号搜索

问题描述

我有以下查询,除了chartIddataType之外的每个过滤器Number都工作正常。我的chartId 字段包含10000234 之类的数据。我想要实现的是,当我输入1000 或234 时,它必须返回具有该chartId 的用户。任何帮助将不胜感激。

const matchNames = {
  $or: [
    { 'userId.firstName': { $regex: term, $options: 'i' } },
    { 'userId.lastName': { $regex: term, $options: 'i' } },
    { 'userId.email': { $regex: term, $options: 'i' } },
    { 'userId.phoneNumber': { $regex: term, $options: 'i' } },
    { 'userId.chartId': { $regex: Number(term) } },
  ],
};

let aggregateDataQuery = [
  {
    $lookup: {
      from: 'users',
      localField: 'userId',
      foreignField: '_id',
      as: 'userId',
    },
  },
  { $match: { ...matchNames } }
]

标签: node.jsmongodbmongooseaggregation-framework

解决方案


没有直接的方法可以做到这一点,您可以使用$regexMatch运算符来匹配内部字段中的正则表达式,

  • $toString从数字转换chartId为字符串
  • $regexMatch匹配输入项,它将返回真/假
const matchNames = {
  $or: [
    { 'userId.firstName': { $regex: term, $options: 'i' } },
    { 'userId.lastName': { $regex: term, $options: 'i' } },
    { 'userId.email': { $regex: term, $options: 'i' } },
    { 'userId.phoneNumber': { $regex: term, $options: 'i' } },
    {
      '$expr': {
        '$regexMatch': {
          'input': { '$toString': { '$toLong': "$userId.chartId" } },
          'regex': term
        }
      }
    }
  ],
};

操场


推荐阅读