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.


Select collection

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

$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.

$dataToSave= array( "sitename" => "", "author" => "MaxJoe" );
Fetch data

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

$result = $collection->find();
foreach($result as $doc)

Update data

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

$newData = array('$set' => array("address" => "1 Smith Lane"));
$collection->update(array("sitename" => ""), $newdata);
Remove data

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

$collection->remove(array("sitename" => "")), array("justOne" => true) );