Press "Enter" to skip to content

How to connect MongoDB with PHP CodeIgniter.


Before starting the coding part, we will first install the MongoDB PHP extension, So here is the step for installing and enabling the MongoDB extension in your WampServer – Here I am using WampServer, If you are using other servers like Xamp, it is somehow similar to Wamp.

  • First we need to download the MongoDB extension for your PHP Version, You can download it from this link =>
  • Then download your extension which matches your PHP Version.
  • Save the php_mongodb.dll file in the ext folder of the PHP folder path, which is in C:/Wamp/bin/PHP/ext
  • Now in php.ini file add extension=php_mongodb.dll //write your downloaded file name here.
  • Restart your WampServer, you have successfully enabled the extension of MongoDB.

Now come to your Project and install the mongo package so start using MongoDB in your Project. Install using composer, and type the below command in your project directory.

composer require mongodb/mongodb
Start using the mongo by calling this method =>  $mongo = new MongoDB\Client("mongodb+srv:// "); //pass here mongo url

Below is the code for saving/inserting data in the collection:-

$mongo = new MongoDB\Client("mongodb+srv:// ");
$collection = $mongo->db->collection_name;   
$collection->insertOne($data); //here $data have all the data in array

For fetching all the data from collection:-

$mongo = new MongoDB\Client("mongodb+srv:// ");
$collection = $mongo->db->collection_name;   

For fetching data from collection with the condition:-

$mongo = new MongoDB\Client("mongodb+srv:// ");
$collection = $mongo->db->collection_name;   
$collection->find({name: ‘Abhishek’});

Happy Coding!

How to create Remember me function in PHP with CodeIgniter?
How to block file download outside from Website using .htaccess