The implementation of randomly obtaining one record in mongodb

Time:2019-10-27

The implementation principle is as follows

1. Query the total number of records in the table first

2. Random acquisition offset is 0 ~ total records – 1

3. When querying, get the skip offset and another record.

Because my test environment PHP has been upgraded to above 7.0, mongodb extension supports php7.0 and above, many methods are different from php5.6. So the code must run above php7.0. If it is a php5.6 environment, you need to modify the code to run.

The code is as follows:

function.php

<?php
//Connect 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 records
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;
}

//Get a record at random
function randOne($conn, $dbname, $collname){

 //Total records
 $total = getCount($conn, $dbname, $collname);

 //Random offset
 $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;
}

//Object to array
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');

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

//Insert 50 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. 'number of test records < br > < br >';

//Get a record randomly, take 5 times
Echo 'randomly obtain a record and sample 5 times < br >';
$result = array();
for($i=0; $i<5; $i++){
 $result[] = randOne($conn, 'testdb', 'user');
}

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

Output:

Number of successfully inserted 50 test records

Get a record randomly, take 5 times


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 PHP code, first create it in mongodbtestdbAnd create users and executeauth

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

The above is the whole content of this article. I hope that the content of this article can be helpful for your study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaer.

Recommended Today

Document the third-party framework you use

BackgroundLibrary: generate shape from label implementation “androidx.appcompat:appcompat:$supportVersion” //for androidx implementation ‘com.noober.background:core:1.6.5’ MagicIndicator: indicator repositories { … maven { url “https://jitpack.io” } } implementation ‘com.github.hackware1993:MagicIndicator:1.7.0’ // for androidx AnyLayer: floating floor (pop up) allprojects { repositories { maven { url ‘https://www.jitpack.io’ } } } implementation ‘com.github.goweii:AnyLayer:3.6.0-androidx’ androidautosize: screen adaptation scheme `implementation ‘me.jessyan:autosize:1.2.1’` glide: image loading implementation […]