Codeigniter: MongoDB



Download the mongo db library for codeigniter from this github repository.

Add files to the appropriate folders on your codeigniter installation. 



Change the configuration on mongodb config files. The following is a sample config file in unauthenticated mode. 

Now you are ready to start using mongodb on your application. 

One more thing, make sure to add mongodb driver on your php installation.

Mongodb config file
 $config['default']['mongo_hostbase'] = 'localhost:27017';
$config['default']['mongo_database'] = 'clp';
$config['default']['mongo_username'] = '';
$config['default']['mongo_password'] = '';
$config['default']['mongo_persist']  = FALSE;
$config['default']['mongo_persist_key']	 = 'ci_persist';
$config['default']['mongo_replica_set']  = FALSE;
$config['default']['mongo_query_safety'] = 'safe';
$config['default']['mongo_suppress_connect_error'] = FALSE;
$config['default']['mongo_host_db_flag']   = FALSE;
Usage on codeigniter controller

First you need to load the mongodb driver on your controller constructor or at the begin of the function. 

Alternately you can auto load the library just like other libraries so that you can use it through out the application without manually loading it each time you use. 

Here is a sample code how to perform insert a sample user data. 


Insert sample
 class Mongotest extends CI_Controller
    function __construct() {

    public function testInsert($username,$name)
        $user = array('username' => $username,
            'name' => $name);
        $this->mongo_db->insert('users', $user);
Some more useful examples

Now its time to write some useful functions.

Here is the query to filter the dataset returned. The following query to gets the records whose publishedtime has less than the supplied value, sorted by publishedtime in descending order( more recent links on the top) and the limit function only fetches 10 records.

  $links = $this->mongo_db
                'status' => 1,
                'siteid' => 1
            ))->where_lt('publishedtime', $start)->order_by(array('publishedtime'=>'desc'))
Paging in mongodb

MongoDB has limit() and skip() function which can be used to implement paging. But using limit()+ skip() functions is not a good way to implement paging when the performance is the concern when there is large set of data. 

So there is an alternative way to implement paging with mongo database using criteria, which does not suffer with performance even with huge data collection. 

Here is the example how to use paging with the criteria along with limit() function.

  public function links($starttime)
        $links = $this->mongo_db
            ->where_lt('publishedtime', $starttime)->order_by(array('publishedtime'=>'desc'))
      $totalrows = count($links);
        if ($totalrows ==$count) {

//there are more records 
// create next link
            $data['nextlink'] = '/linkm/pagesince/' . $links[$totalrows - 1]['publishedtime'];
        } else {

            $data['nextlink'] = '/linkm/pagesince/000';

// Draw view using data

We use the above function to fetch records for next pages. 

At first we pass starttime parameter as the current time value. This returns the collection set (max 10) which has publishedtime leass the the current time. 

To prepare for the next page, the next link will be filled the the publishedtime of the last recrord. 

  public function index()

public function pagesince($starttime)
        $this->links( floatval($starttime));

The general idea is to use the field (the filed which is same for sorting)  value, of the last record,