Lakmal Vithanage Lakmal Vithanage - 6 months ago 12
PHP Question

Revers engineering from mysql to mongodb_most suitable method

In mysql we writes,

SELECT *
FROM Student , Course
WHERE Student.course_id = Course.id
AND Course.name = "English"


we can do the same thing in mongodb as(in PHP)

$m = new MongoClient();
$db = $m->selectDB('test');
$collection1 = new MongoCollection($db, 'Course');
$cursor = $collection1->find(array("name"=>"English"));

$collection2 = new MongoCollection($db, 'Student');


foreach($cursor as $res) {
$cursor = $collection2->find(array("course_id"=>array($in=>$res['id'])));
//do something with the result
}


Or there is another method with prejoin or embedded collections as follow.

$m = new MongoClient();
$db = $m->selectDB('test');
$collection1 = new MongoCollection($db, 'Student');
$cursor = $collection1->find(array("name"=>"Course.English"));

//do something with result


embedded as follow

Student=>array(

id=>...,

Course=>[]

)


1).I'm confused with what is the best solution.
2).What is the best when two collection is used seperatly many times also in a project.

Answer

Since two collections are used frequently, embedding two collection is cause that operations slower. (accessing the data in collections separately.) So in here following code can be used.

$m = new MongoClient();
$db = $m->selectDB('test');
$collection1 = new MongoCollection($db, 'Course');
$cursor = $collection1->find(array("name"=>"English"));

$collection2 = new MongoCollection($db, 'Student');


foreach($cursor as $res) {

    $cursor = $collection2->find(array("course_id"=>array($in=>$res['id'])));
    //do something with the result
}

in here if you need to retrive data from collection2,

$resArr = array();
foreach($cursor as $res) {

array_push($resArr ,$res['id']);

}

  $cursor2 = $collection2->find(array("course_id"=>array($in=>$resArr)));


foreach($cursor2 as $res2) {

    //do something with the result
}
Comments