Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search part of a string in MongoDB?

I have a jquery auto complete script that takes a JSON array and displays it in a table (similar to google suggest). As you type it requests data from a php script.

What I'd like to do is query this data from a MongoDB database as the person types, however I need it to match any part of the selected field.

So I have a field called "Name" that has last name and first name in the same field. If I have a record for "John Smith" Jo Joh john and Sm Smi Smit smith should all match that same record.

Using $collection->find(array('Name' => 'John'); doesn't match my John Smith record however. What am I doing wrong?

like image 519
edude05 Avatar asked Feb 25 '23 19:02

edude05


2 Answers

You would need to use regular expressions for that. Such as

$collection->find(array('Name' => new MongoRegex('/John/i'));
like image 62
The Mighty Rubber Duck Avatar answered Feb 28 '23 17:02

The Mighty Rubber Duck


Using just 'John' you are searching for records where Name matches "John" exactly. You can use regular expressions to match arbitrary sub strings, eg:

$collection->find(array("Name" => "/.*John.*/i"));
like image 40
Hamish Avatar answered Feb 28 '23 16:02

Hamish