2015-01-17 67 views
0

我是mongo db中的新手。我想將mongo db代碼轉換爲codeigniter可理解的格式。Mongo DB到Codeigniter實現

db.demo.find({}, { 
    "person": 1 
}); 
+0

你需要使用的MongoDB庫的https:/ /github.com/vesparny/cimongo-codeigniter-mongodb-library –

回答

2

以下是我的項目中的相關代碼文件。

配置/ mongo.php

$config['mongo_server'] = null; 
$config['mongo_dbname'] = 'mydb'; 
libraries/Mongo.php 

class CI_Mongo extends Mongo 
{ 
    var $db; 

    function CI_Mongo() 
    { 
     // Fetch CodeIgniter instance 
     $ci = get_instance(); 
     // Load Mongo configuration file 
     $ci->load->config('mongo'); 

     // Fetch Mongo server and database configuration 
     $server = $ci->config->item('mongo_server'); 
     $dbname = $ci->config->item('mongo_dbname'); 

     // Initialise Mongo 
     if ($server) 
     { 
      parent::__construct($server); 
     } 
     else 
     { 
      parent::__construct(); 
     } 
     $this->db = $this->$dbname; 
    } 
} 

和樣品控制器

控制器/ posts.php

class Posts extends Controller 
{ 
    function Posts() 
    { 
     parent::Controller(); 
    } 

    function index() 
    { 
     $posts = $this->mongo->db->posts->find(); 

     foreach ($posts as $id => $post) 
     { 
      var_dump($id); 
      var_dump($post); 
     } 
    } 

    function create() 
    { 
     $post = array('title' => 'Test post'); 
     $this->mongo->db->posts->insert($post); 
     var_dump($post); 
    } 
}