Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB php $in and $regex

Tags:

php

mongodb

i'm trying to combine $regex and $in to do simple search.

For example I have a user query of this kind :

$user_query = "for focus red";

In my mongodb collection for each document I have a keywords field. I want to get to get the document where the field keywords is :

{
    keywords :
        [0] => ford,
        [1] => focus,
        [2] => red
}

As you can see the user has done a mistake and typed "for" instead of "ford".

I can get the results with $in if the user types Ford, but I don't know how to combine $regex and $in, I have looked the mongodb doc and php mongo doc.

like image 928
Flyingbeaver Avatar asked Apr 08 '26 03:04

Flyingbeaver


1 Answers

There is my quick snippet:

$user_query = preg_replace("/[[:blank:]]+/"," ", $user_query);
$arr_query = explode(' ', $user_query);

if (count($arr_query) > 1) {
    $tmp = array();

    foreach ($arr_query as $q) {
        $tmp[] = new MongoRegex( "/". $q ."/" );
    }

    $who['keywords'] = array('$in' => $tmp);

} else {
    $who['keywords'] = new MongoRegex( "/". $user_query ."/" );
}

$db->collection->find( $who );
like image 137
Janis Avatar answered Apr 09 '26 15:04

Janis