//** 統(tǒng)計表記錄數(shù) **/ echo ‘count:’.$collection->count().”<br>”; #全部 echo ‘count:’.$collection->count(array(‘type’=>’user’)).”<br>”; #統(tǒng)計‘type’ 為 user 的記錄 echo ‘count:’.$collection->count(array(‘age’=>array(‘$gt’=>50,’$lte’=>74))).”<br>”; #統(tǒng)計大于50小于等于74 echo ‘count:’.$collection->find()->limit(5)->skip(0)->count(true).”<br>”; #獲得實際返回的結(jié)果數(shù) /** * 注:$gt為大于、$gte為大于等于、$lt為小于、$lte為小于等于、$ne為不等于、$exists不存在 */ //** 獲取表中所有記錄 **/ $cursor = $collection->find()->snapshot(); foreach ($cursor as $id => $value) { echo “$id: “; var_dump($value); echo “<br>”; } /** * 注意: * 在我們做了find()操作,獲得$cursor游標之后,這個游標還是動態(tài)的. * 換句話說,在我find()之后,到我的游標循環(huán)完成這段時間,如果再有符合條件的記錄被插入到collection,那么這些記錄也會被$cursor 獲得. * 如果你想在獲得$cursor之后的結(jié)果集不變化,需要這樣做: * $cursor = $collection->find(); */ //** 查詢一條數(shù)據(jù) **/ $cursor = $collection->findOne(); /** * 注意:findOne()獲得結(jié)果集后不能使用snapshot(),fields()等函數(shù); */ //** 設置顯示字段 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節(jié)點) and age!=0 and age<50 **/ $where=array(‘type’=>array(‘$exists’=>true),’age’=>array(‘$ne’=>0,’$lt’=>50,’$exists’=>true)); $cursor = $collection->find($where); //** 分頁獲取結(jié)果集 **/ $cursor = $collection->find()->limit(5)->skip(0); //** 排序 **/ $cursor = $collection->find()->sort(array(‘age’=>-1,’type’=>1)); ##1表示降序 -1表示升序,參數(shù)的先后影響排序順序 //** 索引 **/ $collection->ensureIndex(array(‘age’ => 1,’type’=>-1)); #1表示降序 -1表示升序 $collection->ensureIndex(array(‘age’ => 1,’type’=>-1),array(‘background’=>true)); #索引的創(chuàng)建放在后臺運行(默認是同步運行) $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 */ //** 取得查詢結(jié)果 **/ $cursor = $collection->find(); $array=array(); foreach ($cursor as $id => $value) { $array[]=$value; } |