
Hey techies, in this post I wolud like to explain the functions to perform basic CRUD Operations in Mongo Database using PHP.
In order to get an overview on MongoDB please have a look at the following video.
Now lets start on performing CRUD Operations with PHP. Before you start make sure you have configured your PHP Server with MongoDB PHP Driver. To know how to configure kindly have a look at my previous blogs.
For Windows:
https://mohantk.home.blog/2019/11/02/configuring-mongodb-with-php-in-windows-using-xampp/
Step 1: Establishing connection with MongoDB Server
The first step is to establish a connection with our MongoDB Server.$con = new MongoDB\Driver\Manager("mongodb://localhost:27017");
This line creates an connection object with MongoDB Server. If you have a remote mongodb server then you can replace the uri provided by the remote server.
Step 2: Insert Operation
After making a connection you can perform insert,read,update and delete operations.Lets start with inserting documents.$insert=new MongoDB\Driver\BulkWrite;
$doc=['name'=>"mohan","dept"=>"cse"];
$insert->insert($doc);
$res=$con->executeBulkWrite("mydb.c1",$insert);
You can just replace the values with variables that can receive data from forms when integrated with HTML.
You can check the $res variable with if to verify the insert operation.
Step 3: Read Operation$find=new MongoDB\Driver\Query([]);
$res=$con->executeQuery("mydb.c1",$find);
foreach ($res as $r)
{
echo "Name:". $r->name."Dept:" .$r->dept ."<br>";
}
Instead of displaying right away in php you can pass the data to a html page and display it as a table or in whatever format you need.
If you want to add filters and options you also add it in the first line of code in read operation as follows:$filter = [ 'name' => '<<Your name>>' ];
$options=['sort' => [ 'name' => 1]]
$find = new MongoDB\Driver\Query($filter,$options);
Step 4: Update Operation$writeop=new MongoDB\Driver\BulkWrite;
$crit=['name'="<Your name>"];
$set=['$set'=>['dept'=>"<Your new value>"]];
$writeop->update($crit,$set);
$res=$con->executeBulkWrite("mydb.c1",$writeop);
You can also update multiple keys by adding them to the set array seperated by commas.
Step 4:Delete Operation$delop=new MongoDB\Driver\BulkWrite;
$crit=['name'=>"<Your name>"];
$delop->delete($crit);
$res=$con->executeBulkWrite("mydb.c1",$delop);
Be sure to add your criteria in delete operation or else you would loose all data in your collection.
Please feel free to share how you feel about my blog and do follow my blog to get instant updates about various trends and techs.
If you want any realtime applications to be built using MongoDB please feel free to contact me at
https://mohantk.home.blog/contact-me/
Please use the comment section if you face any errors in performing the CRUD Operations.
See you back!!!
One Comment Add yours