You are on page 1of 4

Next Generation Technologies

Practical #9
Name Abhishek Mishra Roll Number 20302C0037
Subject/Course: NGT
Topic PHP and MongoDB

PHP and MongoDB


Connecting PHP with MongoDB and Inserting, deleting, retrieving and updating

1. Inserting :-
Code:-
<?php
//connect to mongodb
$m=new MongoDB\Driver\Manager("mongodb://localhost:27017");
echo "Connection to database successfully";
$bulk = new MongoDB\Driver\BulkWrite;
$document1 = ['title' => 'one'];
$document2 = ['_id' => 'custom ID', 'title' => 'two'];
$document3 = ['_id' => new MongoDB\BSON\ObjectId, 'title' => 'three'];
$_id1 = $bulk->insert($document1);
$_id2 = $bulk->insert($document2);
$_id3 = $bulk->insert($document3);
var_dump($_id1, $_id2, $_id3);
$result = $m->executeBulkWrite('mydd5.data', $bulk);
echo "Document inserted successfully";
?>
Output Screenshot:-

Vidyalankar School of Information Technology


2. Deleting:-
Code:-
<?php
//connect to mongodb
$m=new MongoDB\Driver\Manager("mongodb://localhost:27017");
echo "Connection to database successfully";
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['_id' => "custom ID"]);
$result = $m->executeBulkWrite('mydd5.data', $bulk);
echo "Document deleted successfully";
?>

Output Screenshot:-

Vidyalankar School of Information Technology


3. Retrieving:-
Code:-
<?php
//connect to mongodb
$m=new MongoDB\Driver\Manager("mongodb://localhost:27017");
echo "Connection to database successfully";
$query = new MOngoDB\DRiver\Query([],[]);
$cursor = $m->executeQuery('mydd5.data',$query);
foreach ($cursor as $document)
{
echo $document->_id;
echo "<br/>";
echo $document->title;
echo "<br/>";
}
?>
Output Screenshot:-

Vidyalankar School of Information Technology


4. Updating:-
Code:-
<?php
//connect to mongodb
$m=new MongoDB\Driver\Manager("mongodb://localhost:27017");
echo "Connection to database successfully";
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['_id' => "custom ID"],
['$set' => ['title' => "mydata"]],
);
$result = $m->executeBulkWrite('mydd5.data',$bulk);
echo "Document updated successfully";
?>

Output Screenshot:-

Vidyalankar School of Information Technology

You might also like