SQL >> Base de Datos >  >> NoSQL >> MongoDB

PHP MongoDB: búsqueda con regex y '$or'

Necesitas especificar algunos campos para tu $in:

$who=array('$or' => array( array('somefield' => array('$in' => array(new MongoRegex($title)))), array('otherotherfield' => array('$in' => array(new MongoRegex($tags)))) )); 

Así funciona, diciendo: si algún campo está en un rango de ciertos valores.

https://docs.mongodb.org/manual/reference/operator/in/

Edición

Puede que eso aún no funcione debido al $regex embebido. Si este es el caso, entonces puedes probar:

$who=array('$or' => array( array('somefield' => new MongoRegex($title)), array('otherotherfield' => new MongoRegex($tags)) )); 

Edición

Si alguna de esas consultas no funciona, puedes hacer:

$who = array('$or' => array()); foreach($arr_query as $q){ $who['$or'][] = array('title' => new MongoRegex("/^$q/")); $who['$or'][] = array('tags' => new MongoRegex("/^$q/")); } 

Algo así debería funcionar; de nuevo, no está probado, pero si la memoria no me falla, eso debería hacerlo.

Otra edición

Esto me funciona perfectamente:

$mongo = new Mongo(); $db = $mongo->tstvid; $videos = $db->videos; $videos->insert(array('title' => 'test1', 'tags' => array('h','h'))); $videos->insert(array('title' => 'test2', 'tags' => array('h','h'))); $videos->insert(array('title' => 'test3', 'tags' => array('h','h'))); $videos->insert(array('title' => 'tst3', 'tags' => array('h','test'))); $user_query = preg_replace("/[[:blank:]]+/"," ", "test"); $arr_query = explode(' ', $user_query); if (count($arr_query) > 1) { $who = array( '$or' => array() ); foreach ($arr_query as $q) { $who['$or'][] = array('title' => new MongoRegex("/^". $q ."/i")); $who['$or'][] = array('title' => new MongoRegex("/^". $q ."/i")); } } else { $regex=new MongoRegex("/^". $user_query ."/i"); $tregex=new MongoRegex("/^". $user_query ."/i"); $who=array( '$or' => array( array('title' => $regex), array('tags' => $tregex) ) ); } $vids=$videos->find($who); $results=""; $i=0; foreach($vids as $vid){ $results .= "<li>".$vid['title']."</li>\n"; $i++; } if($i==0){ $results="<em>No results found</em>"; } echo $results; 

Y produce como salida:

test1 test2 test3 tst3 

Así que no estoy seguro de qué está mal, pero recomendaría verificar que tu script está dividiendo bien las palabras clave y que el esquema se está buscando correctamente, emitiendo también estas consultas en la consola.

Cabe señalar que también probé esto con:

$user_query = preg_replace("/[[:blank:]]+/"," ", "test h"); 

Y funcionó igual de bien.