Php mongodb tutorial – find, insert, update and delete records

PHP Mongodb Tutorial

Mongodb is very popular open source, document based NoSQL database. In this php mongodb tutorial you will learn how to fetch, insert, edit, delete records in a mongodb collection  using php.

Make mongodb php connection:
============================
1.connection with localhost 27017
2.connect with remote host
3.connect with remote host at a given port

<?php
$connection = new MongoClient(); // connects to localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port
?>

Getting a Database:
===================
To select a db use following code in php
<?php
$connection =  new MongoClient();
$db = $connection->myDBname;
if($db){
echo "Database examplesdb selected";
}else{
echo "Database not selected";
}
?>
The database does not need to be created in advance, you can create new databases by selecting them.

Be careful of typos! You can inadvertently create a new database, which can cause confusing errors (here name is misspelled as anme in the second selection:

<?php
$connection = new MongoClient();

$db = $connection->mybiglongdbname;
// do some stuff

$db = $connection->mybiglongdbanme;
// now connected to a different database!
?>


Getting a collection:
=====================
Getting a collection is same as getting databases
<?php
$connection = new MongoClient();
$db = $connection->dbname; //select db
$collection = $db->collectionname; //select collection
or
$collection = $connection->dbname->collectionname; //select collection directly from db
if($collection){
echo "Collection created succsessfully";
}else{
echo "Failed to create collection";
}
?>
A collection is analogous to a table (if you are familiar with relational databases).


Inserting a Document:

====================

  1. Associative arrays are basic object that can be saved to collection in the database.
  2. We can store nested arrays and objects
  3. The driver will store an Associative arrays as an object in the DB.
  4. A numerically indexed array stored as an array  in case the keys start at 0 and are not interrupted, and as an object if the array keys don't start at 0 or have gaps (ie: 0, 1, 4, 5).

example:
========
To insert this document, use MongoCollection::insert():
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$data = array(
    "name" => "MongoDB",
    "type" => "database",
    "count" => 1,
    "info" => (object)array( "x" => 203, "y" => 102),
    "versions" => array("0.9.7", "0.9.8", "0.9.9")
);
$insertData = $collection->insert($data);
if(insertData){
     echo "Document inserted successfully";
}else{
    echo "Failed to insert Document";
}
?>
Note that there is an _id field that has been added automatically to your document.
_id is the "primary key" field. If your document does not specify one, the driver will add one automatically.
If you specify your own _id field, it must be unique to the collection. See the example here:
<?php
$connection = new MongoClient();
$db = $connection->database;

$db->foo->insert(array("_id" => 1));
// this will throw an exception
$db->foo->insert(array("_id" => 1));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1));
?>
By default the driver will ensure the server has acknowledged the write before returning.
You can optionally turn this behaviour off by passing array("w" => 0) as the second argument.
This means that the driver should not wait for the database to acknowledge the write and would not throw the duplicate _id exception.


Finding Documents using MongoCollection::findOne()
==================================================
We can use findOne() to get the single object from the collection.
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$document = $collection->findOne();
echo "Collection selected succsessfully";
?>
From The previous inserted collection.
The above example will output:

array(6) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "4e2995576803fab768000000"
  }
  ["name"]=>
  string(7) "MongoDB"
  ["type"]=>
  string(8) "database"
  ["count"]=>
  int(1)
  ["info"]=>
  array(2) {
    ["x"]=>
    int(203)
    ["y"]=>
    int(102)
  }
  ["versions"]=>
  array(3) {
    [0]=>
    string(5) "0.9.7"
    [1]=>
    string(5) "0.9.8"
    [2]=>
    string(5) "0.9.9"
  }
}


Adding Multiple Documents:
=========================
In order to do more interesting things with queries,
let's add multiple simple documents to the collection.
These documents will just be of the form array( "i" => value );
and we can do this fairly efficiently in a loop:
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

for ( $i = 0; $i < 100; $i++ )
{
    $collection->insert( array( 'i' => $i, "field{$i}" => $i * 2 ) );
}
?>
We can insert arrays with the different keys into the same collection.
Thats why we call mongoDB as "Schema Free"
In the example above each document has an i field, but also a field name in the form of field + $i.


Counting Documents in the collection: (how to check number of rows in the table) for understanding purpose.
======================================
MongoCollection::count()
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$count = $collection->count();
?>


Using Cursor to get all of the documents:
=========================================
In order to get all of the documents in the collection, we use MongoCollection::find()
The find() method returns a MongoCursor object which allows us to iterate over the set of documents that matched our query.
So to query all of the documents and print them out:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
    echo "$id: ";
    var_dump( $value );
}
?>

Setting Criteria for a query: (To get single record in the collection where id = 71)  
============================
hasNext() => Checks if there are any more elements in this cursor.
MongoCursor::getNext() — Advances the cursor to the next result, and returns that result
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => 71 );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>


Getting A Set of Documents With a Query:
=======================================
We can use the query to get a set of documents from our collection.
For example, if we wanted to get all documents where "i" > 50, we could write:
Greater than => '$gt'
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $collection->find( $query );
while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

which should print the documents where "i" > 50. We could also get a range, say 20 < i <= 30:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => array( '$gt' => 20, "\$lte" => 30 ) );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

Update a Document:
=================
MongoCollection::update();
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
// specify the column name whose value is to be updated.
//If no such column than a new column is created with the same name.
$condition = array("i" => 1);
// specify the condition with column name. If no such column exist than no record will update
$newdata = array('$set' => array("i" => "6666"));
if($collection->update($condition, $newdata))
{
    echo 'Record updated successfully</p>';
}
else
{
    echo '<p style="color:red;">Error in update</p>';
}
?>

Remove a Document:
=================
<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;
// specify the column name whose value is to be updated.
//If no such column than a new column is created with the same name.
$condition = array("i" => 1);
// specify the condition with column name. If no such column exist than no record will delete
if($collection->remove($condition, $newdata))
{
    echo 'Record removed successfully</p>';
}
else
{
    echo '<p style="color:red;">Error in delete</p>';
}
?>



Comments