本文實例講述了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'=>'[email protected]); //選擇庫,shell:user demo_db $this->mongodb->selectDB('demo_db'); //選擇集合,db.demo_col.insert(); $rebateCollection = $this->mongodb->getCollection('demo_collection'); $res = $rebateCollection->insert($data); } }
希望本文所述對大家PHP程序設計有所幫助。