JMA
JMA

Reputation: 994

How to search full or partial match with first name and last name in mongodb

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?

Upvotes: 0

Views: 3326

Answers (4)

jasenkoh
jasenkoh

Reputation: 4161

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.

Upvotes: 0

Shaishab Roy
Shaishab Roy

Reputation: 16805

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

Upvotes: 1

Simran
Simran

Reputation: 2820

Try this

{'name': {'$regex': '.*str.*', $options: 'i'}}

Upvotes: 0

ECMAScript
ECMAScript

Reputation: 4649

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, '\\$&');

Upvotes: 0

Related Questions