Integrate MongoDB in CodeIgniter for database operation

In previous article, we discussed about CodeIgniter with MySQL. Today we are going to discuss about CodeIgniter with MongoDB. MongoDB is open source, NoSQL database developed to deal with limitations of SQL Databases. It is very useful where we have no predefined database structure or schema. SQL databases were not designed to cope with scale and agility challenge that face modern application.

Many Organizations, from startup to largest company are choosing Mongodb because of its high performance, scalability or you can do lot of things which you never did with SQL databases like application changes in real time without worrying about any interruptions. You can big change in your application database structure in MongoDB while in other database which follows Relational or NoSQLit’s very difficult.

Mongodb works on concept of collection or documents. Collection is set of documents like table in Relational Database and document is a set of key-value pairs. It’s not necessary that document in same collection have the set same set of columns fields or field structure.

Installation of MongoDB

1. Go to https://www.mongodb.com/download-center and download it as shown below:

 

2. After download it, create mongodb folder in c drive and install it in mongodb folder as shown below. You can give any name of folder and put anywhere in your system. In my case folder name is mongodb and I put that in c drive.

 

3. Click on bin folder of mongoDB then execute mongod.exe file. If it runs without error, you have successfully installed mongoDB. If you are facing some .dlll file error then try with older version of mongoDB like 2.2.0.

Download PHP driver for Mongo

After downloading mongoDB, we will need to install php driver for run mongo in php environment. So these are following step to get php driver and setup in php environment:
1.    Go to https://pecl.php.net/package/mongodb will show following page as shown below. Check your dependence according to your php version, download php mongo driver dll file.

2.    After that put that dll file of ext directory of php folder and add extension of that dll file into php.ini file as also shown below. In my case I renamed dll file to php_mongo.dll you can give any name to it and same name dll extension should be add in php.ini file.

3.    After done all things run php file to see configuration of php with <?phpphpinfo(); ?> this code then you will see following screen as shown below. Find mongo, if all thing corrected will have mongo configuration in browser.

Congratulation you have successfully installed MongoDB and PHP Driver of Mongodb. Now you can make project with Mongodb. Here we will do all basic operation with codeigniter and MongoDB.

Setup Mongo with Codeigniter

1. Create mongoci.php file in libraries folder of application with following code :

<?php

classMongoci extends Mongo 
	{

	// hurrdurr nobody's going to look here

		function __construct()
			{   			//allow mongo to use 64bit ints
				//ini_set('mongo.native_long', 1);
				//ini_set('mongo.long_as_object', 1);
		// Fetch CodeIgniter instance
				$ci = get_instance();
		// Load Mongo configuration file
				$ci->load->config('mongoci');

		// Fetch Mongo server and database configuration
				$server = $ci->config->item('mongo_server');
				$username = $ci->config->item('mongo_username');
				$password = $ci->config->item('mongo_password');
				$dbname = $ci->config->item('mongo_dbname');
				try {
					if($ci->config->item('mongo_auth') === FALSE)
					parent::__construct("mongodb://" . $server . "/" . $dbname);
				else
					parent::__construct("mongodb://$username:$password@$server/$dbname");
					$this->db = $this->$dbname;
					} 
				catch(MongoConnectionException $e) 
					{
			//Don't show Mongo Exceptions as they can contain authentication info
						$_error =&load_class('Exceptions', 'core');
						exit($_error->show_error('MongoDB Connection Error', 'A MongoDB error occured while trying to connect to the database!', 'error_db'));           
					} 
				catch(Exception $e) 
					{
						$_error =&load_class('Exceptions', 'core');
						exit($_error->show_error('MongoDBError',$e->getMessage(), 'error_db'));        
					}
			}
		public function cursor_data($data)
			{
				$final_array = array();
				foreach(iterator_to_array($data) as $data_array)
					{
						$final_array[] = $data_array;
					}
				return $final_array;
			}		
}

?>

 

2.    Create another file mongoci.php in config folder of application with following below code and create database discussdesk or give it name whatever you want. You can create database through robomongo which is UI tool like phpmyadmin. To download robomongo, go to its official site  or click on https://robomongo.org/download  this link.

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['mongo_server'] = 'localhost';
$config['mongo_dbname'] = 'discussdesk'; // Databse Name
$config['mongo_auth']   = FALSE;
$config['mongo_username'] = '';
$config['mongo_password'] = '';

?>

Simple CURD operation in codeigniter with MongoDB

1.    Now open controller folder which is in application folder and make a new php file, give it name what you want controller name. In my case controller name is home. Make sure your controller or file name should be same as shown below:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {
	public function __construct()
	{
	   parent::__construct();
	    //helpers
	   $this->load->helper('url');
	}

	public function index()
	{
		$this->load->view(‘home_view');
	}

}
?>

Here I have created home.php file in controller and make a function index to show view then load home view php file in index function. In my case home_view is view file of  View Section.

Now we have no home_view file so we have to create home_view file in View and put these following code into home_view.php file.

For Insertion Record in Codeigniter with MongoDB

  • In home controller add insert record function with following code as shown below and load insert_article view file in insert_record  controller function.
<?php
public function insert_record()
	{
		  $data = $this->input->post();
		if(!empty($data))
		  {
			  $this->home_model->insert_article($data);
		  }
		  $this->load->view('insert_article');	
	}

?>
  • Create home_model  Model with following code to insert record into article table:
<?php
classHome_model extends CI_Model
	{
		
		public function __construct()
		{
			parent::__construct();
			$this->load->library('mongoci');
		}
		
		public function insert_article($data)
		{
   $query = $this->mongoci->db->article->insert($data);
if($query=='1')
		   {
			echo "Record Inserted";
		}			
	}
?>
  • Create insert_article file in view folder to show view for inserting article

Fill Article name, description and date then it will go insert_record function of home control to insert new record.

For Showing Record in Codeigniterwith MongoDB

  • Create show_records function in home controller to show all articles from article Table as shown below:
public function show_records()
	{
		$data['article'] = $this->home_model->show_articles();
		$this->load->view('show_article',$data);
	}
  • Create show_articles function to fetch all record from article table with select query :
<?php
public function mongo_cursor($cursor)  // iterator to cursor and return array 
		{
			$data=array();
			foreach($cursor as $user_data)
			{
			  $data[]=$user_data;
			}
			return $data;
}	
	public function show_articles()
		{
			$query = $this->mongoci->db->article->find();
return $this->mongo_cursor($query);
		}

?>
  • Create show_article.php file in view folder to show all articles as like this:
<table align="center" border='1'>
<tr>
<td>No.</td>
<td>Article Name</td>
<td>Article Descrption</td>
<td>Date</td>

</tr>
<?php $i =1; foreach($article as $article_data){ ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $article_data['name']; ?></td>
<td><?php echo $article_data['description']; ?></td>
<td><?php echo $article_data['date']; ?></td>

</tr>
<?php $i++; } ?>

</table>

For Updating  Record in Codeigniterwith MongoDB

Createupdate_record function in home controller with following code to update article as shown below:

<?php
public function update_article($id)
	{
		$data = $this->input->post();
		if(!empty($data))
		{
		  $this->home_model->update_article($data,$id);
		}
		$data['article'] = $this->home_model->show_article($id);
		$this->load->view('update_article',$data);
	}

?>
  • Create update_article function in home_model function to update article with following code as below:
<?php
public function update_article($data,$id)
		{
			$where = array('_id'=> new MongoId($id));
			$update = array('$set'=>$data);
			$this->mongoci->db->article->update($where,$update);
			echo "Record Updated";		
}

?>
  • Create update_article.php view file to show all records which will be updated .A user will select and update one of them.

For Deleting  Record in Codeigniter with MongoDB

  • Createdelete_article function in home controller with following code to delete  article as shown below:
<?php
public function delete_record()
	{
		$data['article'] = $this->home_model->show_articles();
		$this->load->view('delete_records',$data);	
		
	}
	public function delete_article($id)
	{
	 $this->home_model->delete_article($id);
	redirect('home/delete_record');
	}

?>
  • Add another function in Model with name delete_article with paremeter as shown below:
<?php
public function delete_article($id)
		{
			$where = array('_id'=> new MongoId($id));
			$this->mongoci->db->article->remove($where);				
		}

?>
  • Create View file in which user will select and delete article as shown below:
<table align="center" border='1'>
<tr>
<td>No.</td>
<td>Article Name</td>
<td>Article Descrption</td>
<td>Date</td>
<td>Action</td>

</tr>
<?php $i =1; foreach($article as $article_data){ ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $article_data['name']; ?></td>
<td><?php echo $article_data['description']; ?></td>
<td><?php echo $article_data['date']; ?></td>
<td><a href="<?php echo base_url(); ?>index.php/home/delete_article/<?php echo $article_data['_id']; ?>">Delete </a></td>

</tr>
<?php $i++; } ?>

</table>

Now we have completed all basic database operation still have any confusion in codeigniter and Mongodb, feel free to ask us in comment section.

Share this Article on Social Media

All of my Scripts are ready to customized as per your requirement. Feel free to contact for script customization.

Contact me at discussdesk@gmail.com

"Note : It will be charged as per your customization requirement :)"

Get Updates, Scripts & Other Tutorials to Directly to your Email

Over 20000+ Happy Readers already subscribed. (We don't send spam email). Every email subscriber can get our latest updates and download our 100+ scripts.

Comments