How to connect MongoDB with PHP CodeIgniter.

December 20, 2022 · 2 min read

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.

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;   
$collection->find()->toArray(); 

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
Share on Facebook
Facebook
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Pin on Pinterest
Pinterest