0

How to search full or partial match with first name and last name in mongodb? I tried using this,

{"name":{ $regex: str, $options: 'i'}}

But it is only for full match of the string. Can I use regex for partial match?

JMA
  • 974
  • 3
  • 13
  • 41
  • What is the regex you are using to search? – str Jan 02 '17 at 09:39
  • str is a name "John Test" – JMA Jan 02 '17 at 09:54
  • `str` should be a Regex, not the actual string. MongoDB uses Perl compatible regular expressions. Refer http://perldoc.perl.org/perlre.html to create regex which satisfies your need – RaR Jan 02 '17 at 10:42

4 Answers4

1

For this type of search better to create text index. mongo shell command to create text index for name field.

db.colectionName.createIndex( { name: "text" } );

then you can search using $text and $search

var text = 'John Test''
db.collectionName.find({ $text: { $search: text  } });

for this query you will get if name contain john or test and this is case insensitive

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
0

I have to do this for my project, how does this work for you? {"name":new RegExp('^'+name, 'i')} you may need to encode the string first str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

ECMAScript
  • 4,439
  • 4
  • 21
  • 29
  • @JohnArellano Escape the regex characters, otherwise input with regex symbols such as `*` or `.` will be parsed as regex. – ECMAScript Jan 02 '17 at 19:17
0

Try this

{'name': {'$regex': '.*str.*', $options: 'i'}}
Simran
  • 2,364
  • 1
  • 12
  • 19
0

I have responded to similar question here, combining text index and regex pattern makes it work nicely. Note, text index is searching by terms so if you try to search for padavan by supplying pad you won't get what you are expecting having only text index in place.

Community
  • 1
  • 1
jasenkoh
  • 4,011
  • 2
  • 19
  • 24