6

In mongodb the equivalent to sql "like" operator is

db.users.find({"shows": /m/})

Using nodejs/javascript I want to dynamically change letter, based on url paramater.

I have tried

letter = req.params.letter;

db.users.find({"shows": '/' + letter + '/'})

This doesn't work, I guess because the slashes are now strings are interpreted differently.

jamjam
  • 3,171
  • 7
  • 34
  • 39

3 Answers3

16

One way to do it, according to the documentation page:

db.users.find( { shows : { $regex : letter } } );
mindandmedia
  • 6,800
  • 1
  • 24
  • 33
  • https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex – Mahesh K Oct 02 '16 at 10:39
  • This is working fine but i want to search from multiple fields see below my code – Pritesh Mahajan Oct 06 '16 at 08:19
  • var searchVar = req.body.search; Product.find({name : { $regex : searchVar },sku : { $regex : searchVar }},function(error,fetchSearchProduct){}); I need get same result with both cases "test" and "Test" . now its working for "Test" not for "test" – Pritesh Mahajan Oct 06 '16 at 08:19
2

+1 for mindandmedia on the syntax. However, please remember, that if you want the query to use an index efficiently, you have to use prefix queries (also called rooted regexps) like /^prefix/

Your query is likely to be horribly slow otherwise - see the note in the docs here:

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

Adam Comerford
  • 21,336
  • 4
  • 65
  • 85
0

You can try this:

let filter = "Dynamic";

let str = /.*Raj.*/;
console.log(str);
console.log(typeof(str));


let stra = eval(`/.*${filter}+.*/`);
console.log(stra);
console.log(typeof(stra));
Dino
  • 7,779
  • 12
  • 46
  • 85