Since Codeigniter does not officially support MongoDB at this time, MongoDB Codeigniter integration is not very easy currently. So, in this tutorial I will explain how we can install MongoDB with Codeigniter using official PHP drivers provided by MongoDB. Let’s get started :

Prerequisites :

A VPS(Virtual Private Server) with a web server (e.g. Apache, NGINX), PHP and MongoDB server installed. If you have a shared hosting account, check with your service provider if they have MongoDB installed.

Install the mongodb extension

The MongoDB PHP Library is a high-level abstraction for the MongoDB PHP driver. So, we need to install the mongodb extension before we can use the MongoDB PHP Library for MongoDB codeigniter integration. Follow below steps:

PECL maintains mongodb extension for PHP, so we’ll install it from there.

The above library can be loaded with additional parameters from the application code. This gives us flexibility to load the library from application at run time and override the configuration from config file.

Additionally, if you are not using authentication, you can use

$mongo['connection'] = new MongoDB\Client("mongodb://$host:$port");

for connection instead of the statement mentioned in the above code. But make sure you use proper authentication in production or with publicly accessible installation.

Create a controller method to verify the installation

Now, create a file Mongo_test.php in the controller directory and paste below code in it. We will insert some test values and verify that installation is working as expected:

If you want to use the config file parameters, then you can skip loading the mongodb library with additional parameters, as explained in the code.

Now, access mongo_test from your web application e.g. if you have CI installed on your localhost, then go to http://localhost/index.php/mongo_test . If everything is setup correctly, you should see the values from test array we just inserted.

If there is any issue, just make sure all steps are followed correctly. If there is till any problem, let me know the details using the comments.