node.js - mongodb部分号搜索
问题描述
我有以下查询,除了chartId
dataType之外的每个过滤器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 } }
]
解决方案
没有直接的方法可以做到这一点,您可以使用$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
}
}
}
],
};
推荐阅读
- sql - 蜂巢窗口功能
- python-2.7 - Barh 为 -: 'unicode' 和 'float' 引发错误不受支持的操作数类型
- javascript - R Shiny:在 UI 上的 textInput 中检查正则表达式
- amazon-web-services - 如何向触发管道的人发送电子邮件通知?
- node.js - Npm 错误“未定义内部绑定”
- string - 如果字符串不相等,vb.net 中的正确运算符是什么?
- java - 在 Java Azure 函数中使用可选参数的正确方法
- python - Python:从保存在 Mag、Degrees 中的文件中加载复数
- typescript - 具有类型化创建和修补方法的 Typescript 基类
- reactjs - 在 React 谷歌地图中显示我当前的位置图标