开发者

How do I search part of a string in MongoDB?

开发者 https://www.devze.com 2023-01-26 07:45 出处:网络
I have a jquery auto complete script that takes a JSON arra开发者_Go百科y and displays it in a table (similar to google suggest). As you type it requests data from a php script.

I have a jquery auto complete script that takes a JSON arra开发者_Go百科y 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?


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

$collection->find(array('Name' => new MongoRegex('/John/i'));


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"));
0

精彩评论

暂无评论...
验证码 换一张
取 消