mongodb 隨機(jī)獲取一條記錄的方法
原理:
1.先查詢表中的記錄總數(shù)
2.隨機(jī)獲取偏移量為0~總記錄數(shù)-1
3.查詢時(shí)skip偏移量,再獲取1條記錄
因本人測試環(huán)境PHP已升級到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; } // 對象轉(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; $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.'條測試記錄數(shù)<br><br>'; // 隨機(jī)獲取一條記錄,抽5次 echo '隨機(jī)獲取一條記錄,抽5次<br>'; $result = array(); for($i=0; $i<5; $i++){ $result[] = randOne($conn, 'testdb', 'user'); } echo '<pre>'; print_r($result); echo '</pre>'; ?>
輸出:
成功插入50條測試記錄數(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 ) )
測試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" } )
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
- mongodb中隨機(jī)獲取1條記錄的實(shí)現(xiàn)方法
- 1億條記錄的MongoDB數(shù)據(jù)庫隨機(jī)查詢性能測試
- MongoDB 導(dǎo)出導(dǎo)入備份恢復(fù)數(shù)據(jù)詳解及實(shí)例
- mongodb 3.2.5安裝詳細(xì)過程
- MongoDB 主從復(fù)制實(shí)例講解
- python實(shí)現(xiàn)爬蟲數(shù)據(jù)存到 MongoDB
- MongoDB windows解壓縮版安裝教程詳解
- 深入理解MongoDB分片的管理
- Yii框架連接mongodb數(shù)據(jù)庫的代碼
- MongoDB安裝圖文教程
- ASP.NET MVC4使用MongoDB制作相冊管理
相關(guān)文章
springboot整合mongodb?changestream的示例代碼
Chang?Stream(變更記錄流)?是指collection(數(shù)據(jù)庫集合)的變更事件流,應(yīng)用程序通過db.collection.watch()這樣的命令可以獲得被監(jiān)聽對象的實(shí)時(shí)變更,本文給大家介紹springboot整合mongodb?changestream的示例代碼,感興趣的朋友一起看看吧2022-02-02MongoDB中常用操作$addToSet、$pop和$rename
本文主要介紹了MongoDB中常用操作$addToSet、$pop和$rename,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-12-12Mongodb解決不能連接到服務(wù)器的錯(cuò)誤問題
這篇文章主要介紹了Mongodb解決不能連接到服務(wù)器的錯(cuò)誤問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01Mongodb基本操作與Python連接mongodb并進(jìn)行基礎(chǔ)操作的方法
mongodb是基于分布式文件存儲(chǔ)的nosql(非關(guān)系型)數(shù)據(jù)庫,本文分享了mongodb的基礎(chǔ)操作和Python連接并操作mongodb的基礎(chǔ)方法,基礎(chǔ)的不能再基礎(chǔ)了2018-09-09