如何在 MongoDB 查询中使用正则表达式变量 [英] How can I use a regex variable in a query for MongoDB

查看:31
本文介绍了如何在 MongoDB 查询中使用正则表达式变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据我构建的正则表达式查询 MongoDB 中的文档.例如我构建了一个简单的正则表达式,如下所示,它是 Nodejs 中随机字母和随机数的组合

I would like to make query MongoDB for documents based on a regex expression that I contruct. For e.g I have constructed a simple regex as follows that is a combination of a random letter and a random number for in Nodejs

var randnum = Math.floor((Math.random() * 10) + 1);
var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z'];
var randletter = alpha[Math.floor(Math.random() * alpha.length)];
var val = randletter + randnum + '.*;

我已经为正则表达式变量尝试了各种组合,例如

I have tried various combinations for the regex variable like

var stream = collection.find({"FirstName": /val/).stream();
&&
var stream = collection.find({"FirstName": /$val/).stream();
&&
var stream = collection.find({"FirstName": {$in : [{$regex:val}]}}).stream()
&&
var stream = collection.find({"FirstName": {$in : [{$regex:$val}]}}).stream()

没有 o 它似乎有效.但是,当我编写实际的正则表达式时,我得到了例如

None o it seem to work. However when I write the actual regex I get the records for e.g.

var stream = collection.find({"FirstName": /J.*/).stream();

任何帮助将不胜感激.

谢谢甘尼许

推荐答案

您需要使用 RegExp 构造函数作为 /.../ 语法仅用于文字.

You need to create a regular expression object from the string using the RegExp constructor as the /.../ syntax is only for use with literals.

var stream = collection.find({"FirstName": new RegExp(val)}).stream();

这篇关于如何在 MongoDB 查询中使用正则表达式变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆