1

I'm trying to convert a database from MySQL to MongoDB but I have a problem. I do not know how the query should look for MongoDB.

   $hd='';
   $count = count($args[1]);
   for($i=0;$i<$count-1;$i++){
       $hd.="playerId='" . $args[1][$i] . "' OR ";
   }
   $hd.="playerId='".$args[1][$count-1]."'";
   $h1=mysql_query(sprintf("SELECT * FROM player where ".$hd));

Anyone know how to fix it?

Community
  • 1
  • 1
Pastan
  • 19
  • 4
  • Which is why one should use a DAL, such as PDO. :) – Itai Sagi Sep 02 '12 at 11:02
  • 2
    What do you mean with "how to fix it"? This looks more like a rewriting request, with no prior attempts of your own. See [MongoDB queries](http://www.mongodb.org/display/DOCS/Advanced+Queries) to read up on it first, then the according [PHP manual section](http://www.php.net/manual/en/mongo.sqltomongo.php). – mario Sep 02 '12 at 11:06
  • 1
    That's only a query for SQL not for Mongo. What do you mean by your question? Also you are using vulnerable code also you are using soon to be deprecated `mysql_` driver. – Sammaye Sep 02 '12 at 11:06
  • 1
    On a side note: Your MySQL query could be improved by making a list of the args: `$list = implode(",", $args[1])` then put it into the statement with the `in` clause: `SELECT * FROM player where playerId in ($list)` – Jørgen R Sep 02 '12 at 11:06

2 Answers2

0

Your question is similar to Mongo db select where in array of _id?

I'm not that familiar with MongoDB, but instead of using multiple OR you can use IN() statement should make your query more readable:

$h1 = mysql_query(
    "SELECT * FROM player where playerId IN (" . implode(", ", $args[1]) . ")"
);

As for MondoDB I think this should get you the result you need:

$m = new Mongo();
$db = $m->selectDB("database"); // your db
$mc = new MongoCollection($db, 'player');
$mc->find(
    array(
        'playerId' => array(
            '$in' => $args[1]
        )
    )
);

If you find some grammar errors, please don't shoot me :)

Community
  • 1
  • 1
Ivan Hušnjak
  • 3,493
  • 3
  • 20
  • 30
0

PHP - MongoDB Advanced Queries

$collection->find([
    'playerId' => ['$in' => [1, 2, 3]]
]);
Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68