php mongodb获取总数,mongodb 随机获取一条记录的方法

原理:

1.先查询表中的记录总数

2.随机获取偏移量为0~总记录数-1

3.查询时skip偏移量,再获取1条记录

因本人测试环境PHP已升级到7.0以上,mongodb扩展使用支持php7.0以上的扩展,很多方法与php5.6不同。因此代码必须在php7.0以上运行。如果是php5.6环境,需要修改代码才能运行。

代码如下:

function.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;

}

// 插入数据

function add($conn, $dbname, $collname, $data, $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);

// 插入数据

$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;

}

// 获取总记录数

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;

}

// 随机获取一条记录

function randOne($conn, $dbname, $collname){

// 总记录数

$total = getCount($conn, $dbname, $collname);

// 随机偏移

$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;

}

// 对象转为数组

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

require('function.php');

// 连接mongodb

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

// 插入50条数据记录

$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.'条测试记录数
';

// 随机获取一条记录,抽5次

echo '随机获取一条记录,抽5次
';

$result = array();

for($i=0; $i<5; $i++){

$result[] = randOne($conn, 'testdb', 'user');

}

echo '

';

print_r($result);

echo '

';

?>

输出:

成功插入50条测试记录数

随机获取一条记录,抽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创建testdb及创建用户和执行auth。方法如下:

use testdb

db.createUser(

{

"user":"root",

"pwd":"123456",

"roles":[{"role" : "readWrite", "db":"testdb"}]

}

)

db.auth(

{

"user":"root",

"pwd":"123456"

}

)

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值