Online Snippets Library

Perform Simple CRUD in Mongodb with PHP

MongoDB is a document database that provides high performance.Manipulating data in mongodb is very easy.CRUD stands for create, read, update, and delete.In below example we will perform CURD operation.

Example

Select collection

Select a collection is similer like select a database in MySQL or SQL.

<?php
$m = new MongoClient('mongodb://localhost:27017');
$db = $m->manish; // manish is db name
$collection = $db->users; // users is collection name
?>
Add data

We need to define an array and insert it.

<?php
$dataToSave= array( "sitename" => "www.tutsway.com", "author" => "MaxJoe" );
$collection->insert($dataToSave);
?>
Fetch data

To Fetch data from mongodb we will use find() method.

<?php
$result = $collection->find();
foreach($result as $doc)
  print_r($doc);

?>
Update data

To Update data from mongodb we will use update() method.

<?php
$newData = array('$set' => array("address" => "1 Smith Lane"));
$collection->update(array("sitename" => "www.tutsway.com"), $newdata);
?>
Remove data

To Update data from mongodb we will use remove() method.

<?php
$collection->remove(array("sitename" => "www.tutsway.com")), array("justOne" => true) );
?>