คอมพิวเตอร์และอินเตอร์เน็ต,บรรยายวิชาการ,วิจัย,ศึกษากุรอาน,E-Book

วันพฤหัสบดีที่ 29 กรกฎาคม พ.ศ. 2564

ตัวอย่าCode PHP MongoDB

 


//read all data
//$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$mng = new MongoDB\Driver\Manager("mongodb://root:testtest@localhost:27017");
$query = new MongoDB\Driver\Query([]); 
$rows = $mng->executeQuery("q_alert_db.qa_sys_user", $query);
foreach ($rows as $man) {
 echo "$man->fname  $man->lname<br>";
}


//read with sort and limit 5
//$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$mng = new MongoDB\Driver\Manager("mongodb://root:testtest@localhost:27017");
$query = new MongoDB\Driver\Query([], ['sort' => [ 'fname' => 1], 'limit' => 5]);  
/* 'sort' => [ 'fname' => -1]  */ 
$rows = $mng->executeQuery("q_alert_db.qa_sys_user", $query);
foreach ($rows as $man) {
    echo "$man->fname  $man->lname<br>";
}


//filter and wilde card
//$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$mng = new MongoDB\Driver\Manager("mongodb://root:testtest@localhost:27017");
$filter = [ 'office_id' => array('$regex' => '12')]; 
$options = ['projection' => ['_id' => 0],'sort' => ['office_id' => -1]]; 
$query = new MongoDB\Driver\Query($filter, $options);     
$res = $mng->executeQuery('q_alert_db.qa_sys_user', $query);
$c=1;
foreach ($res as $man) {
    if(substr($man->office_id,0,2)=='12'){ //แก้ปัญหา ที่จะแสดงทุกค่าที่มี 12
        echo "$c $man->fname  $man->lname $man->office_id<br>";
        $c++;
    }
}


//insert or write data
//$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$mng = new MongoDB\Driver\Manager("mongodb://root:testtest@localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$doc = ['_id' => new MongoDB\BSON\ObjectID, 
        'username' => 'Toyota', 
        'password' => 'aaa',
        'login_type' =>'1',
        'login_status' =>'1'
    ];
$bulk->insert($doc);
/*
$bulk->update(['name' => 'Audi'], ['$set' => ['price' => 52000]]);
$bulk->delete(['name' => 'Hummer']);
*/
$mng->executeBulkWrite('q_alert_db.qa_sys_user', $bulk);
echo "Insert Data Already\n";



ไม่มีความคิดเห็น: