MongoDB a method of randomly acquiring a record _mongodb

Source: Internet
Author: User
Tags auth create index mongodb php code

Principle:

1. First query the total number of records in the table

2. Random get Offset is 0~ total record number-1

3. Skip offset at query, and get 1 records

Because I test the environment PHP has upgraded to more than 7.0, MongoDB extended Use support php7.0 above the expansion, many methods and php5.6 different. The code must therefore run above php7.0. If it is a php5.6 environment, you need to modify the code to run it.

The code is as follows:

function.php

<?php//Connection MONGODB function conn ($host, $user, $passwd) {$server = ' mongodb://'. $user. ': $passwd. '
  @ '. $host;
  try{$conn = new Mongodb\driver\manager (); The catch (Mongodb\driver\exception\connectionexception $e) {throw new errorexception (' Unable to connect-to-DB server. E Rror: '.
  $e->getmessage (), 31);
return $conn; }//Insert Data Function Add ($conn, $dbname, $collname, $data, $index) {//CREATE INDEX $cmd = Array (' createindexes ' => $c Ollname, ' indexes ' => Array (Array (' name ' => ' index ', ' key ' => $index, ' NS ' =& Gt $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; //Gets the total number of 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;

  ///randomly fetch a record function Randone ($conn, $dbname, $collname) {//total record number $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 ');

Connection 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. ' Test record number <br><br> ';

Randomly get a record, smoke 5 times
echo ' randomly get a record, smoke 5 times <br> ';
$result = Array ();
For ($i =0 $i <5; $i + +) {
  $result [] = Randone ($conn, ' TestDB ', ' user ');
}

Echo ' <pre> ';
Print_r ($result);
Echo ' </pre> ';
? >

Output:

Successful insertion of 50 test records

randomly fetch a record and smoke 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 your PHP code, you first need to create TESTDB and create users 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" 
  } 
) 

SOURCE Download Address: Click to view

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.