1. 程式人生 > >PHP操作MongoDB例項

PHP操作MongoDB例項

從mysql中把資料匯入到MongoDB中做測試.

//連線資料庫
$link = mysql_connect("127.0.0.1","root","123456");
mysql_select_db("jiang", $link);
mysql_query("set names utf-8");
$sql = "select `id`,`name`,`address` from member";
$result = mysql_query($sql);
//例項化Mongo
$mongo = new Mongo(); 
//選擇資料庫
$db = $mongo->selectDB("post")->member;
//從資料庫中取出資料存入mongodb
while($row = mysql_fetch_array($result,MYSQLI_ASSOC)){
	$res = $db->insert(array("vid"=>(float)$row['id'],"name"=>$row['name'],"address"=>$row['address']));
}
//查詢當前文件的資料總數
$tp = $db->find()->count();
$page = isset($_GET['page']) ? max(1,(int)$_GET['page']) : 1;
//每頁顯示的數量
$pagesize = 50;
//設定分頁
$skip = ($page-1) * $pagesize;
//總頁數
$totalPage = ceil($tp/$pagesize);
//獲取資料
$data = $db->find()->fields(array("_id"=>0))->sort(array('_id'=>-1))->skip($skip)->limit($pagesize);
$list = array();
foreach ($data as $key => $val) {
	$list[] = $val;
}