Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo Query with Regex in Node JS operating ON A VARIABLE

I have a problem here. I want to query my MongoDB in my Node JS file using something like LIKE for a conventional relational db. The problem is the thing I want to LIKE to is not a literal...it is a variable! I have found no good way to do this as of yet. Here was the "durrr first try" shot I took at it:

var result = postData.replace(/\+/g,' ').substring(5);
db.testlogwiki.find({"line_text" : /result/ };
//predictably only matches to the literal "result" as opposed to my variable

testlogwiki is made in Mongo...I have it running and this does mach to db entries with "line_text" containing "result" literally.

It seems like a very simple question...

like image 777
PinkElephantsOnParade Avatar asked May 23 '12 21:05

PinkElephantsOnParade


People also ask

Can I use regex in MongoDB query?

In MongoDb, can use like using MongoDb reference operator regular expression(regex).

How regex works in MongoDB?

MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support.

How do I use wildcard search in MongoDB?

Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.

How do I find special characters in MongoDB?

To search a string with special characters in MongoDB document, you can use \. Here, we have special character $ in our string.


2 Answers

Try this one:

db.testlogwiki.find({"line_text" : new RegExp(result) };
like image 200
Sergio Tulentsev Avatar answered Oct 04 '22 04:10

Sergio Tulentsev


Both will work

db.testlogwiki.find({"line_text" : new RegExp(result, 'i') }; // to make this case insensitive 

or

db.testlogwiki.find( { line_text: { $regex: result[, $options: 'i'] } } );
like image 29
Tridib Avatar answered Oct 04 '22 03:10

Tridib