<?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;
}
}
?>
<?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.'条测试记录数<br><br>';
// 随机获取一条记录,抽5次
echo '随机获取一条记录,抽5次<br>';
$result = array();
for($i=0; $i<5; $i++){
$result[] = randOne($conn, 'testdb', 'user');
}
echo '<pre>';
print_r($result);
echo '</pre>';
?>
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 ) )
use testdb
db.createUser(
{
"user":"root",
"pwd":"123456",
"roles":[{"role" : "readWrite", "db":"testdb"}]
}
)
db.auth(
{
"user":"root",
"pwd":"123456"
}
)
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有