Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to MongoDB?

Tags:

php

mongodb

I like to implement

"SELECT * FROM TABLE_NAME 
    WHERE 
         name like '$query_string' or 
         title like '%$query_string%' or 
         tags like '%$query_string%'"

to mongoDB, and I tried

$condition = array('$or' => 
   array('writer'=> array('name'=>"$query_string"), 
          'title'=> new MongoRegex("/$query_string/"),  
          'tags' => new MongoRegex("/$query_string/") ));

and this does not work.

What is proper way to implement that SQL to mongoDB?

like image 202
jwchang Avatar asked Oct 24 '22 02:10

jwchang


1 Answers

Here's how I construct a case-insensitive, "contains" term

$containsTerm = new MongoRegex(sprintf('/%s/i', preg_quote($term, '/')));

So your condition might look like

$condition = array('$or' => array(
    'writer.name' => $term,
    'title'       => $containsTerm,
    'tags'        => $containsTerm
));

Apologies if the condition array is wrong, I typically use the Doctrine ODM

like image 148
Phil Avatar answered Oct 27 '22 09:10

Phil