| //** 統計表記錄數 **/echo ‘count:’.$collection->count().”<br>”; #全部echo ‘count:’.$collection->count(array(‘type’=>’user’)).”<br>”; #統計‘type’ 為 user 的記錄echo ‘count:’.$collection->count(array(‘age’=>array(‘$gt’=>50,’$lte’=>74))).”<br>”; #統計大於50小於等於74echo ‘count:’.$collection->find()->limit(5)->skip(0)->count(true).”<br>”; #獲得實際返回的結果數/*** 注:$gt為大於、$gte為大於等於、$lt為小於、$lte為小於等於、$ne為不等於、$exists不存在*///** 擷取表中所有記錄 **/$cursor = $collection->find()->snapshot();foreach ($cursor as $id => $value) {echo “$id: “; var_dump($value); echo “<br>”;}/*** 注意:* 在我們做了find()操作,獲得$cursor遊標之後,這個遊標還是動態.* 換句話說,在我find()之後,到我的遊標迴圈完成這段時間,如果再有合格記錄被插入到collection,那麼這些記錄也會被$cursor 獲得.* 如果你想在獲得$cursor之後的結果集不變化,需要這樣做:* $cursor = $collection->find();*///** 查詢一條資料 **/$cursor = $collection->findOne();/*** 注意:findOne()獲得結果集後不能使用snapshot(),fields()等函數;*///** 設定顯示欄位 age,type 列不顯示 **/$cursor = $collection->find()->fields(array(“age”=>false,”type”=>false));$cursor = $collection->find()->fields(array(“user”=>true)); //只顯示user 列/*** 我這樣寫會出錯:$cursor->fields(array(“age”=>true,”type”=>false));*///** 設定條件 (存在type,age節點) and age!=0 and age<50 **/$where=array(‘type’=>array(‘$exists’=>true),’age’=>array(‘$ne’=>0,’$lt’=>50,’$exists’=>true));$cursor = $collection->find($where);//** 分頁擷取結果集 **/$cursor = $collection->find()->limit(5)->skip(0);//** 排序 **/$cursor = $collection->find()->sort(array(‘age’=>-1,’type’=>1)); ##1表示降序 -1表示升序,參數的先後影響排序次序//** 索引 **/$collection->ensureIndex(array(‘age’ => 1,’type’=>-1)); #1表示降序 -1表示升序$collection->ensureIndex(array(‘age’ => 1,’type’=>-1),array(‘background’=>true)); #索引的建立放在後台運行(預設是同步運行)$collection->ensureIndex(array(‘age’ => 1,’type’=>-1),array(‘unique’=>true)); #該索引是唯一的/*** ensureIndex (array(),array(‘name’=>’索引名稱’,‘background’=true,’unique’=true))* 詳見:http://www.php.net/manual/en/mongocollection.ensureindex.php*///** 取得查詢結果 **/$cursor = $collection->find();$array=array();foreach ($cursor as $id => $value) {$array[]=$value;} |