国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MongoDB > 正文

mongodb中隨機獲取1條記錄的實現方法

2020-03-14 13:07:09
字體:
來源:轉載
供稿:網友

實現原理如下

    1.先查詢表中的記錄總數

    2.隨機獲取偏移量為0~總記錄數-1

    3.查詢時skip偏移量,再獲取1條記錄

因本人測試環境php已升級到7.0以上,mongodb擴展使用支持php7.0以上的擴展,很多方法與php5.6不同。因此代碼必須在php7.0以上運行。如果是php5.6環境,需要修改代碼才能運行。

代碼如下:

function.php

<?php// 連接mongodbfunction conn($host, $user, $passwd){ $server = 'mongodb://'.$user.':'.$passwd.'@'.$host; try{  $conn = new MongoDB/Driver/Manager(); } catch (MongoDB/Driver/Exception/ConnectionException $e){  throw new ErrorException('Unable to connect to db server. Error:' . $e->getMessage(), 31); } return $conn;}// 插入數據function add($conn, $dbname, $collname, $data, $index){ // 創建索引 $cmd = array(  'createIndexes' => $collname,  'indexes' => array(   array(    'name' => 'index',    'key' => $index,    'ns' => $dbname.'.'.$collname   )  ) ); $command = new MongoDB/Driver/Command($cmd); $conn->executeCommand($dbname, $command); // 插入數據 $bulk = new MongoDB/Driver/BulkWrite(); $inserted = 0; if($data){  foreach($data as $k=>$v){   $bulk->insert($v);  }  $result = $conn->executeBulkWrite($dbname.'.'.$collname, $bulk);  $inserted = $result->getInsertedCount(); } return $inserted;}// 獲取總記錄數function getCount($conn, $dbname, $collname){ $cmd = array(  'count' => $collname,  'query' => array() ); $command = new MongoDB/Driver/Command($cmd); $result = $conn->executeCommand($dbname, $command); $response = current($result->toArray()); if($response->ok==1){  return $response->n; } return 0;}// 隨機獲取一條記錄function randOne($conn, $dbname, $collname){ // 總記錄數 $total = getCount($conn, $dbname, $collname); // 隨機偏移 $skip = mt_rand(0, $total-1); $filter = array(); $options = array('skip'=>$skip, 'limit'=>1); $query = new MongoDB/Driver/Query($filter, $options); $cursor = $conn->executeQuery($dbname.'.'.$collname, $query); $result = array(); if($cursor){  foreach($cursor as $v){   $v = objectToArray($v);   unset($v['_id']);   $result[] = $v;  } } return $result? $result[0] : $result;}// 對象轉為數組function objectToArray($obj){ $arr = is_object($obj) ? get_object_vars($obj) : $obj; if(is_array($arr)){  return array_map(__FUNCTION__, $arr); }else{  return $arr; }}?>

demo.php

<?phprequire('function.php');// 連接mongodb$conn = conn('localhost','testdb','root','123456');// 插入50條數據記錄$data = array();// 索引$index = array('user'=>true);for($i=0; $i<50; $i++){ $data[] = array(  'user' => 'test_user_'.str_pad($i, 4, '0', STR_PAD_LEFT) );}$inserted = add($conn, 'testdb', 'user', $data, $index);echo '成功插入'.$inserted.'條測試記錄數<br><br>';// 隨機獲取一條記錄,抽5次echo '隨機獲取一條記錄,抽5次<br>';$result = array();for($i=0; $i<5; $i++){ $result[] = randOne($conn, 'testdb', 'user');}echo '<pre>';print_r($result);echo '</pre>';?>

輸出:

成功插入50條測試記錄數

隨機獲取一條記錄,抽5次

Array( [0] => Array  (   [user] => test_user_0017  ) [1] => Array  (   [user] => test_user_0026  ) [2] => Array  (   [user] => test_user_0004  ) [3] => Array  (   [user] => test_user_0043  ) [4] => Array  (   [user] => test_user_0023  ))

測試php代碼,首先需要在mongodb創建testdb及創建用戶和執行auth

方法如下:

use testdbdb.createUser(  {   "user":"root",   "pwd":"123456",   "roles":[{"role" : "readWrite", "db":"testdb"}]  } ) db.auth(  {   "user":"root",   "pwd":"123456"  } ) 

總結

以上就是這篇文章的全部內容,希望本文的內容對大家的學習或者工作能有所幫助,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。


注:相關教程知識閱讀請移步到MongoDB頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 秦安县| 扬中市| 酉阳| 古浪县| 福建省| 台江县| 内黄县| 辽宁省| 彩票| 盐池县| 横峰县| 文登市| 旺苍县| 千阳县| 凤庆县| 南澳县| 江陵县| 淄博市| 枣强县| 平江县| 长岛县| 博白县| 清流县| 镇远县| 山阳县| 吉隆县| 贞丰县| 丽江市| 米脂县| 杂多县| 潞西市| 龙川县| 腾冲县| 东源县| 灯塔市| 舟曲县| 河北省| 九江市| 湛江市| 资源县| 那曲县|