PHP Mongodb API 及使用

发表时间:2010-08-11 文章分类:mongodb 阅读:59979

文章链接:http://www.webzone8.com/article/19.html
  

<?php  
/*** Mongodb类** examples:  
* $mongo = new HMongodb("127.0.0.1:11223");
* $mongo->selectDb("test_db");
* 创建索引
* $mongo->ensureIndex("test_table", array("id"=>1), array('unique'=>true));
* 获取表的记录
* $mongo->count("test_table");
* 插入记录
* $mongo->insert("test_table", array("id"=>2, "title"=>"asdqw"));
* 更新记录
* $mongo->update("test_table", array("id"=>1),array("id"=>1,"title"=>"bbb"));
* 更新记录-存在时更新,不存在时添加-相当于set
* $mongo->update("test_table", array("id"=>1),array("id"=>1,"title"=>"bbb"),array("upsert"=>1));
* 查找记录
* $mongo->find("c", array("title"=>"asdqw"), array("start"=>2,"limit"=>2,"sort"=>array("id"=>1)))
* 查找一条记录
* $mongo->findOne("$mongo->findOne("ttt", array("id"=>1))", array("id"=>1));
* 删除记录
* $mongo->remove("ttt", array("title"=>"bbb"));
* 仅删除一条记录
* $mongo->remove("ttt", array("title"=>"bbb"), array("justOne"=>1));
* 获取Mongo操作的错误信息
* $mongo->getError();
*/
 
 
class HMongodb {  
 
    //Mongodb连接  
    var $mongo;  
 
    var $curr_db_name;  
    var $curr_table_name;  
    var $error;  
 
    /**
    * 构造函数
    * 支持传入多个mongo_server(1.一个出问题时连接其它的server 2.自动将查询均匀分发到不同server)
    *
    * 参数:
    * $mongo_server:数组或字符串-array("127.0.0.1:1111", "127.0.0.1:2222")-"127.0.0.1:1111"
    * $connect:初始化mongo对象时是否连接,默认连接
    * $auto_balance:是否自动做负载均衡,默认是
    *
    * 返回值:
    * 成功:mongo object
    * 失败:false
    */
 
    function __construct($mongo_server, $connect=true, $auto_balance=true)  
    {  
        if (is_array($mongo_server))  
        {  
            $mongo_server_num = count($mongo_server);  
            if ($mongo_server_num > 1 && $auto_balance)  
            {  
                $prior_server_num = rand(1, $mongo_server_num);  
                $rand_keys = array_rand($mongo_server,$mongo_server_num);  
                $mongo_server_str = $mongo_server[$prior_server_num-1];  
                foreach ($rand_keys as $key)  
                {  
                    if ($key != $prior_server_num - 1)  
                    {  
                        $mongo_server_str .= ',' . $mongo_server[$key];  
                    }  
                }  
            }  
            else  
            {  
                $mongo_server_str = implode(',', $mongo_server);  
            }                  }  
        else  
        {  
            $mongo_server_str = $mongo_server;  
        }  
        try {  
            $this->mongo = new Mongo($mongo_server, array('connect'=>$connect));  
        }  
        catch (MongoConnectionException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }  
    }  
 
    function getInstance($mongo_server, $flag=array())  
    {  
        static $mongodb_arr;  
        if (emptyempty($flag['tag']))  
        {  
            $flag['tag'] = 'default';          }  
        if (isset($flag['force']) && $flag['force'] == true)  
        {  
            $mongo = new HMongodb($mongo_server);  
            if (emptyempty($mongodb_arr[$flag['tag']]))  
            {  
                $mongodb_arr[$flag['tag']] = $mongo;  
            }  
            return $mongo;  
        }  
        else if (isset($mongodb_arr[$flag['tag']]) && is_resource($mongodb_arr[$flag['tag']]))  
        {  
            return $mongodb_arr[$flag['tag']];  
        }  
        else  
        {  
            $mongo = new HMongodb($mongo_server);  
            $mongodb_arr[$flag['tag']] = $mongo;  
            return $mongo;                  }          }  
 
    /**
    * 连接mongodb server
    *
    * 参数:无
    *
    * 返回值:
    * 成功:true
    * 失败:false
    */
 
    function connect()  
    {  
        try {  
            $this->mongo->connect();  
            return true;  
        }  
        catch (MongoConnectionException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }  
    }  
 
    /**
    * select db
    *
    * 参数:$dbname
    *
    * 返回值:无
    */
 
    function selectDb($dbname)  
    {  
        $this->curr_db_name = $dbname;  
    }  
 
    /**
    * 创建索引:如索引已存在,则返回。
    *
    * 参数:
    * $table_name:表名
    * $index:索引-array("id"=>1)-在id字段建立升序索引
    * $index_param:其它条件-是否唯一索引等
    *
    * 返回值:
    * 成功:true
    * 失败:false
    */
 
    function ensureIndex($table_name, $index, $index_param=array())  
    {  
        $dbname = $this->curr_db_name;  
        $index_param['safe'] = 1;  
        try {  
            $this->mongo->$dbname->$table_name->ensureIndex($index, $index_param);  
            return true;  
        }  
        catch (MongoCursorException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }  
    }  
 
    /**
    * 插入记录
    *
    * 参数:
    * $table_name:表名
    * $record:记录
    *
    * 返回值:
    * 成功:true
    * 失败:false
    */
 
    function insert($table_name, $record)  
    {  
        $dbname = $this->curr_db_name;  
        try {  
            $this->mongo->$dbname->$table_name->insert($record, array('safe'=>true));  
            return true;  
        }  
        catch (MongoCursorException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }  
    }  
 
    /**
    * 查询表的记录
    *
    * 参数:
    * $table_name:表名
    *
    * 返回值:表的记录
    */
 
    function count($table_name)  
    {  
        $dbname = $this->curr_db_name;  
        return $this->mongo->$dbname->$table_name->count();  
    }  
 
    /**
    * 更新记录
    *
    * 参数:
    * $table_name:表名
    * $condition:更新条件
    * $newdata:新的数据记录
    * $options:更新选择-upsert/multiple
    *
    * 返回值:
    * 成功:true
    * 失败:false
    */
 
    function update($table_name, $condition, $newdata, $options=array())  
    {  
        $dbname = $this->curr_db_name;  
        $options['safe'] = 1;  
        if (!isset($options['multiple']))  
        {  
            $options['multiple'] = 0;          }  
        try {  
            $this->mongo->$dbname->$table_name->update($condition, $newdata, $options);  
            return true;  
        }  
        catch (MongoCursorException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }          }  
 
    /**
    * 删除记录
    *
    * 参数:
    * $table_name:表名
    * $condition:删除条件
    * $options:删除选择-justOne
    *
    * 返回值:
    * 成功:true
    * 失败:false
    */
 
    function remove($table_name, $condition, $options=array())  
    {  
        $dbname = $this->curr_db_name;  
        $options['safe'] = 1;  
        try {  
            $this->mongo->$dbname->$table_name->remove($condition, $options);  
            return true;  
        }  
        catch (MongoCursorException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }          }  
 
    /**
    * 查找记录
    *
    * 参数:
    * $table_name:表名
    * $query_condition:字段查找条件
    * $result_condition:查询结果限制条件-limit/sort等
    * $fields:获取字段
    *
    * 返回值:
    * 成功:记录
    * 失败:false
    */
 
    function find($table_name, $query_condition, $result_condition=array(), $fields=array())  
    {  
        $dbname = $this->curr_db_name;  
        $cursor = $this->mongo->$dbname->$table_name->find($query_condition, $fields);  
        if (!emptyempty($result_condition['start']))  
        {  
            $cursor->skip($result_condition['start']);  
        }  
        if (!emptyempty($result_condition['limit']))  
        {  
            $cursor->limit($result_condition['limit']);  
        }  
        if (!emptyempty($result_condition['sort']))  
        {  
            $cursor->sort($result_condition['sort']);  
        }  
        $result = array();  
        try {  
            while ($cursor->hasNext())  
            {  
                $result[] = $cursor->getNext();  
            }  
        }  
        catch (MongoConnectionException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }  
        catch (MongoCursorTimeoutException $e)  
        {  
            $this->error = $e->getMessage();  
            return false;  
        }  
        return $result;  
    }  
 
    /**
    * 查找一条记录
    *
    * 参数:
    * $table_name:表名
    * $condition:查找条件
    * $fields:获取字段
    *
    * 返回值:
    * 成功:一条记录
    * 失败:false
    */
 
    function findOne($table_name, $condition, $fields=array())  
    {  
        $dbname = $this->curr_db_name;  
        return $this->mongo->$dbname->$table_name->findOne($condition, $fields);  
    }  
 
    /**
    * 获取当前错误信息
    *
    * 参数:无
    *
    * 返回值:当前错误信息
    */
 
    function getError()  
    {  
        return $this->error;  
    }  
}  
 
?>
 
有趣的视频娱乐一下

原文链接:http://www.webzone8.com/article/19.html

用户评论

用户【27.150.243*****】说:very good put up, i definitely love this web site, keep on it

用户【27.150.243*****】说:This really answered my downside, thanks!

用户【27.150.243*****】说:Thanks so much for providing individuals with remarkably splendid possiblity to read articles and blog posts from this blog. It is often very amazing and full of a great time for me personally and my office colleagues to search your site really three times weekly to see the fresh tips you will have. Of course, I am just usually fascinated with the extraordinary pointers you serve. Selected 4 areas in this posting are completely the finest we have all had.

用户【27.150.243*****】说:You made some first rate factors there. I regarded on the internet for the difficulty and found most people will associate with together with your website.

用户【27.150.243*****】说:Hey! I just wish to give an enormous thumbs up for the nice info you will have here on this post. I will likely be coming back to your blog for more soon.

用户【27.150.243*****】说:I抦 impressed, I need to say. Actually not often do I encounter a blog that抯 each educative and entertaining, and let me tell you, you may have hit the nail on the head. Your concept is excellent; the problem is something that not enough individuals are talking intelligently about. I am very completely satisfied that I stumbled throughout this in my seek for one thing relating to this.

用户【27.150.245*****】说:I just wanted to type a quick note in order to say thanks to you for some of the stunning concepts you are writing on this website. My rather long internet look up has now been paid with wonderful facts and techniques to go over with my pals. I would express that most of us visitors actually are really fortunate to live in a superb site with many special individuals with helpful concepts. I feel very much fortunate to have discovered your web page and look forward to tons of more entertaining times reading here. Thanks once again for everything.

用户【27.150.245*****】说:I found your weblog website on google and test a number of of your early posts. Continue to keep up the very good operate. I just extra up your RSS feed to my MSN News Reader. In search of forward to studying extra from you in a while!?

用户【27.150.245*****】说:I must point out my admiration for your kind-heartedness giving support to men and women who really need help on in this niche. Your real dedication to passing the message all-around ended up being amazingly practical and has without exception permitted men and women like me to attain their objectives. Your amazing warm and helpful guidelines means a whole lot to me and substantially more to my office workers. Thanks a ton; from everyone of us.

用户【27.150.245*****】说:Whats up! I simply want to give a huge thumbs up for the nice info you could have here on this post. I will probably be coming again to your weblog for more soon.

用户【27.150.240*****】说:Aw, this was a very nice post. In idea I wish to put in writing like this moreover ?taking time and precise effort to make a very good article?however what can I say?I procrastinate alot and certainly not seem to get something done.

用户【27.150.240*****】说:After examine just a few of the blog posts on your web site now, and I really like your manner of blogging. I bookmarked it to my bookmark web site checklist and can be checking back soon. Pls take a look at my website as well and let me know what you think.

用户【27.150.240*****】说:I and my pals were actually looking through the good tactics found on your website while quickly got an awful suspicion I had not expressed respect to the blog owner for them. All the people are actually for this reason glad to read them and have now without a doubt been making the most of them. Thanks for turning out to be really accommodating and then for utilizing certain quality themes millions of individuals are really needing to learn about. My personal honest regret for not saying thanks to sooner.

用户【114.92.24.*****】说:楼主有没有试过插入中文呀,我怎么插不进去呀?

发表评论

姓名:*
邮箱:*
网站:*