Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $regex mongodb query in node js not working


From node js, i trying to retrieve the documents based on the keyword with case-insensitive. When i try directly from the mongo db console , i am able to see the result.

db.users.findOne({"displayName":{$regex: /.*abc./, $options:"i"}})

But when i try the same in node js, i am getting empty result.

var selector = { "displayName": {$regex: "/.*abc./", $options:"i"}}

is this due to regular expression not in javascript.
Can anyone please help me in this.

like image 302
Soorya Prakash Avatar asked Feb 18 '15 12:02

Soorya Prakash


People also ask

How regex works in MongoDB?

MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions.


3 Answers

The $regex value needs to be either the string pattern to match or a regular expression object. When passing a string pattern, you don't include the / delimitters like you're doing in your node.js code.

So either of these would work in node.js:

var selector = {"displayName": {$regex: ".*abc.", $options:"i"}}

OR

var selector = {"displayName": {$regex: /.*abc./, $options:"i"}}
like image 135
JohnnyHK Avatar answered Oct 17 '22 02:10

JohnnyHK


could you please try this one, It works for me.

var getValue = "abc";

db.users.findOne({ displayName: new RegExp(regexValue, "i") }, function(err, res) {
  if (err) {
    console.log(err);
  } else {
    console.log(res.length);
  }
});
like image 15
Soe Naing Tun Avatar answered Oct 17 '22 00:10

Soe Naing Tun


In mongodb console try this query

db.users.findOne({"displayName":{$regex: ".*abc", $options:"i"}})

and in nodejs var selector = users.find({ "displayName": {$regex: ".*abc", $options:"i"}})

here users = is a collection name

like image 5
Ganesh Apune Avatar answered Oct 17 '22 01:10

Ganesh Apune