濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > mongodb 隨機(jī)獲取一條記錄的方法

mongodb 隨機(jī)獲取一條記錄的方法

熱門(mén)標(biāo)簽:云南外呼系統(tǒng) 老虎洗衣店地圖標(biāo)注 怎么投訴地圖標(biāo)注 呼和浩特電銷(xiāo)外呼系統(tǒng)加盟 電銷(xiāo)機(jī)器人是什么軟件 杭州人工電銷(xiāo)機(jī)器人價(jià)格 濟(jì)南電銷(xiāo)機(jī)器人加盟公司 廣州長(zhǎng)安公司怎樣申請(qǐng)400電話 蘋(píng)果汽車(chē)租賃店地圖標(biāo)注

原理:

1.先查詢(xún)表中的記錄總數(shù)

2.隨機(jī)獲取偏移量為0~總記錄數(shù)-1

3.查詢(xún)時(shí)skip偏移量,再獲取1條記錄

因本人測(cè)試環(huán)境PHP已升級(jí)到7.0以上,mongodb擴(kuò)展使用支持php7.0以上的擴(kuò)展,很多方法與php5.6不同。因此代碼必須在php7.0以上運(yùn)行。如果是php5.6環(huán)境,需要修改代碼才能運(yùn)行。

代碼如下:

function.php

?php
// 連接mongodb
function 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;
}

// 插入數(shù)據(jù)
function add($conn, $dbname, $collname, $data, $index){

  // 創(chuàng)建索引
  $cmd = array(
    'createIndexes' => $collname,
    'indexes' => array(
      array(
        'name' => 'index',
        'key' => $index,
        'ns' => $dbname.'.'.$collname
      )
    )
  );
  $command = new MongoDB\Driver\Command($cmd);
  $conn->executeCommand($dbname, $command);

  // 插入數(shù)據(jù)
  $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;
}

// 獲取總記錄數(shù)
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;
}

// 隨機(jī)獲取一條記錄
function randOne($conn, $dbname, $collname){

  // 總記錄數(shù)
  $total = getCount($conn, $dbname, $collname);

  // 隨機(jī)偏移
  $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;
}

// 對(duì)象轉(zhuǎn)為數(shù)組
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

?php
require('function.php');

// 連接mongodb
$conn = conn('localhost','testdb','root','123456');

// 插入50條數(shù)據(jù)記錄
$data = array();

// 索引
$index = array('user'=>true);

for($i=0; $i50; $i++){
  $data[] = array(
    'user' => 'test_user_'.str_pad($i, 4, '0', STR_PAD_LEFT)
  );
}

$inserted = add($conn, 'testdb', 'user', $data, $index);
echo '成功插入'.$inserted.'條測(cè)試記錄數(shù)br>br>';

// 隨機(jī)獲取一條記錄,抽5次
echo '隨機(jī)獲取一條記錄,抽5次br>';
$result = array();
for($i=0; $i5; $i++){
  $result[] = randOne($conn, 'testdb', 'user');
}

echo 'pre>';
print_r($result);
echo '/pre>';
?>

輸出:

成功插入50條測(cè)試記錄數(shù)

隨機(jī)獲取一條記錄,抽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
    )

)

測(cè)試php代碼,首先需要在mongodb創(chuàng)建testdb及創(chuàng)建用戶和執(zhí)行auth。方法如下:

use testdb

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

db.auth( 
  { 
    "user":"root", 
    "pwd":"123456" 
  } 
) 

源碼下載地址:點(diǎn)擊查看

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

您可能感興趣的文章:
  • mongodb中隨機(jī)獲取1條記錄的實(shí)現(xiàn)方法
  • 1億條記錄的MongoDB數(shù)據(jù)庫(kù)隨機(jī)查詢(xún)性能測(cè)試
  • MongoDB 導(dǎo)出導(dǎo)入備份恢復(fù)數(shù)據(jù)詳解及實(shí)例
  • mongodb 3.2.5安裝詳細(xì)過(guò)程
  • MongoDB 主從復(fù)制實(shí)例講解
  • python實(shí)現(xiàn)爬蟲(chóng)數(shù)據(jù)存到 MongoDB
  • MongoDB windows解壓縮版安裝教程詳解
  • 深入理解MongoDB分片的管理
  • Yii框架連接mongodb數(shù)據(jù)庫(kù)的代碼
  • MongoDB安裝圖文教程
  • ASP.NET MVC4使用MongoDB制作相冊(cè)管理

標(biāo)簽:興安盟 泰安 遼陽(yáng) 自貢 無(wú)錫 廈門(mén) 玉林 雞西

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《mongodb 隨機(jī)獲取一條記錄的方法》,本文關(guān)鍵詞  mongodb,隨機(jī),獲取,一條,記錄,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《mongodb 隨機(jī)獲取一條記錄的方法》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于mongodb 隨機(jī)獲取一條記錄的方法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    盐山县| 浦城县| 安新县| 即墨市| 明光市| 沙洋县| 溧水县| 贵溪市| 江山市| 沁源县| 建平县| 呼玛县| 黔东| 慈利县| 塘沽区| 博兴县| 内江市| 新巴尔虎右旗| 水城县| 扬州市| 滨海县| 扎兰屯市| 利津县| 东台市| 都安| 富顺县| 县级市| 南川市| 共和县| 板桥市| 钟祥市| 广宗县| 贵南县| 毕节市| 喀喇沁旗| 玉门市| 赣州市| 民勤县| 双柏县| 伊宁市| 新竹县|