本文实例讲述了PHP封装的简单连接MongoDB类。分享给大家供大家参考,具体如下:
1. 封装MongoDB类
<?php class MongoDB { private $database; private $mongo; function __construct() { $this->mongo = new MongoClient("mongodb://user:password@server_address:port/admin"); $this->database = $this->mongo->selectDB("data"); } { return $this->database->selectCollection($collection); } //获取所有的集合名 function getCollections() { return $this->database->getCollectionNames(); } //选数据库 function selectDB($db) { $this->database = $this->mongo->selectDB($db); } }
2. 简单调用,insert数据。
class DemoController extends CI_Controller { function __construct() { parent::__construct(); //CI中加载类 $this->load->library('mongo_lib', '', 'mongodb'); } //插入一条数据 function create() { $data = array('name'=>'mike','email'=>'abc@163.com); //选择库,shell:user demo_db $this->mongodb->selectDB('demo_db'); //选择集合,db.demo_col.insert(); $rebateCollection = $this->mongodb->getCollection('demo_collection'); $res = $rebateCollection->insert($data); } }