Mongo DB到Codeigniter的实现

时间:2015-01-17 11:03:01

标签: mongodb codeigniter

我是mongo db的新手。我想将mongo db代码翻译成codeigniter可理解的格式。

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

1 个答案:

答案 0 :(得分: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);
    }
}