<?php
class MongoServer{
private $server = 'localhost:27017';
private $options = array('connect'=>true);
public $client;
public $db;
public $dbname='test';
public function __construct($server, $options=false, $dbname=''){
$server && $this->server = $server;
$dbname && $this->dbname = $dbname;
$options && count($options) && $this->options = $options;
$this->ConnectDb();
}
private function ConnectDb(){
try{
#链接数据库
$this->client = new MongoClient($this->server, $this->options);
}catch(Exception $e){
exit('connect MongoDB failed!');
}
try{
#选库
$this->db = $this->client->selectDB($this->dbname);
}catch(Exception $e){
exit('select DataBase failed!');
}
}
function table($name){
$this->collect = $this->db->__get($name);
return new MongoCURD($this->collect);
}
}
class MongoCURD{
public $table;
function __construct($table){
$this->table = $table;
}
public function select($map=array()){
$cursor = $this->table->find($map);
return iterator_to_array($cursor);
}
public function find($map=array()){
$cursor = $this->table->findOne($map);
return $cursor;
}
public function count(){
return $this->table->count();
}
public function handsById($id, $action="find"){
if(!(bool)$id){
return false;
}
$mongoId = new MongoId($id);
switch($action){
case "delete":
$rs = $this->table->remove(array('_id'=>$mongoId), array('justOne'=>true));
if($rs['n']){
return $rs['n'];
}else{
return false;
}
break;
default:
$cursor = $this->table->findOne(array('_id'=>$mongoId));
return $cursor;
break;
}
}
public function update($map, $data, $isnew=false){
return $this->table->update($map, $data, array('upsert'=>$isnew));
}
// 将id转成可查询对象
public function mongoId($id){
return new MongoId($id);
}
}
function db($dbname){
return new MongoServer('192.168.1.188:11001', false, $dbname);
}
$person = db('test')->table('person');
$map = array('_id'=>$person->mongoId('56ea176ba3f97f58350e653'));
$onedata = $person->find($map);
$onedata['age'] = 93;
$rs = $person->update($map, $onedata, true);
var_dump($rs);
exit;
【笔记】初学mongodb之自定义类
最新推荐文章于 2021-02-16 04:23:45 发布