English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Randomly Obtain in MongoDB1Implementation Method of Record

The implementation principle is as follows

    1.Firstly, query the total number of records in the table

    2.Randomly obtain an offset of 0 to the total number of records-1

    3.When querying, the skip offset is used, and then the data is retrieved1records

Because my test environment php has been upgraded to7.0 or above, the mongodb extension supports php7.0 or above, many methods of the mongodb extension support php5.6differences. Therefore, the code must be run in php7.0 or above. If it is php5.6The environment requires modifying the code to run.

The code is as follows:

function.php

<?php
// Connect to 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;
}
// Insert data
function add($conn, $dbname, $collname, $data, $index){
 // Create 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);
 // Insert data
 $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;
}
// Get total record count
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;
}
// Randomly retrieve a record
function randOne($conn, $dbname, $collname){
 // Total number of records
 $total = getCount($conn, $dbname, $collname);
 // Random offset
 $skip = mt_rand(0, $total-1);
 
 $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;63; $result[0] : $result;
}
// Object to array
function objectToArray($obj){
 $arr = is_object($obj) ?63; get_object_vars($obj) : $obj;
 if(is_array($arr)){
  return array_map(__FUNCTION__, $arr);
 }else{
  return $arr;
 }
}
?>

demo.php

<?php
require('function.php');
// Connect to mongodb
$conn = conn('localhost','testdb','root','123456);
// Insert50 data records
$data = array();
// Index
$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 'Successfully inserted '.$inserted.' test records<br><br>';
// Randomly fetch a record, draw5times
echo 'Randomly fetch a record, draw5times<br>';
$result = array();
for($i=0; $i<5; $i++{
 $result[] = randOne($conn, 'testdb', 'user');
}
echo '<pre>';
print_r($result);
echo '</pre>';
?>

Output:

Successfully inserted50 times of test record number

Randomly fetch a record, draw5times

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
  )
)

To test the PHP code, you first need to create testdb and create a user and execute auth in MongoDB.

The method is as follows:

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

Summary

That's all for this article. I hope the content of this article can be helpful to everyone's learning or work. If you have any questions, you can leave a message for communication. Thank you for your support of the Shouting Tutorial.

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like