MongoDB and PHP

I assume you have mongodb installed. If you haven’t installed you should by following these links as per your operating system.

MongoDB with PHP Installation

For Windows

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

For Mac

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/

For Ubuntu or debian based you can follow

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

Install PHP Drivers

After MongoDB is installed you need to install mongoDB php drivers. Here is official guide.

http://docs.mongodb.org/ecosystem/drivers/php/

If any problems installing driver ,Let me know at comments section below.

Don’t forget to add line extension=mongo.so in php.ini file and restart server.

Connect To mongoDB using php MongoClient class

Basic steps to connect are :

  • Create Connection
  • Select Database
  • Select Collection

We connect to mongoDB using MongoClient() class like this

<?php

// connect

$m = new MongoClient();

// select a database

$db = $m->tutstub;

// select a collection

$collection = $db->users;

?>

Now you can query on collection using $collection variable.For authentication see bonus points below.

Note: MongoDB stores all data in documents, which are JSON-style data structures composed of field-and-value pairs:

{ "item": "pencil", "qty": 500, "type": "no.2" }

Insert document

To insert data into users we will use insert method and it take array of values as parameter.

$insert=$collection->insert(array("username"=>"john"));

Please note that insert method will return boolean value 1 on success and will output error message if any. So to get output in browser you need to verify using if statement.

if($insert){  
    echo 'Success';
}

Find document

In mongoDB we have two method find() and findOne() which are generally used to get data from collection.

These methods too accept array as parameter. So code looks like this

$data=$collection->find(array("email"=>"john@doe.com"));

If there is any such mail,It will return MongoCursor Object which is array of array of documents.

So you can’t just use print_r($data) instead you have to use

foreach($data as $users){  
    print_r($users); 
}

This will output the document as an array.


Find single document

It returns only single document but in form single dimensional array

$data=$collection->findOne(array("email"=>"john@doe.com"));
print_r($data);  

Update document

Suppose you want to change email from previous to new so you will use this way.Here $set acts similar to as in mysql query

$update=$collection->update(array("email" => "oldEmail"),
                            array('$set' => array("email" => "newEmail")));

Delete document

Simply use remove method and pass array to it.

$delete=$collection->remove(array("email"=>"john@doe.com"));

Extra methods


Limit

$data=$collection->find()->limit(2);

You can also pass array in find() for specific result with limit.


Skip

$data=$collection->find()->skip(2);

Mainly used for pagination!


Count

$data=$collection->find()->count();

or to count everything in collection

$data=$collection->count();


Sort

$data=$collection->find()->sort(array("email"=>1));

Here sorting results by email and 1 means ascending order and -1 is descending order.


Explain

$data=$collection->find()->explain();

Explain is used for debugging purpose.


Bonus Points

  1. Don’t use $m=new Mongo(); //It is deprecated use MongoClient

  2. For authentication use
    new MongoClient(“mongodb://username:password@host:port/dbname”)

  3. You don’t need to create database and collection manually if you are just defining them in your code,Your first operation via your code automatically create database and collection for you defined in your code.

  4. To prevent injection in MongoDB , yes mongoDB is vulnerable to attack similar to sql injection. You should use casting and add (string) before values like this.

    $data=$collection->find(array(“email”=>(string)$email));

  5. There is also a MongoDB PHP book which you
    can buy at http://shop.oreilly.com/product/0636920022381.do

Mysql To Mongo Table

CREATE TABLE USERS (a Number, b Number)   Implicit or use MongoDB::createCollection().
INSERT INTO USERS VALUES(1,1)   $db->users->insert(array(“a” => 1, “b” => 1));
SELECT a,b FROM users   $db->users->find(array(), array(“a” => 1, “b” => 1));
SELECT * FROM users WHERE age=33   $db->users->find(array(“age” => 33));
SELECT a,b FROM users WHERE age=33   $db->users->find(array(“age” => 33), array(“a” => 1, “b” => 1));
SELECT a,b FROM users WHERE age=33 ORDER BY name   $db->users->find(array(“age” => 33), array(“a” => 1, “b” => 1))->sort(array(“name” => 1));
SELECT * FROM users WHERE age>33   $db->users->find(array(“age” => array(‘$gt’ => 33)));
SELECT * FROM users WHERE age<33   $db->users->find(array(“age” => array(‘$lt’ => 33)));
SELECT * FROM users WHERE name LIKE “%Joe%”   $db->users->find(array(“name” => new MongoRegex(“/Joe/”)));
SELECT * FROM users WHERE name LIKE “Joe%”   $db->users->find(array(“name” => new MongoRegex(“/^Joe/”)));
SELECT * FROM users WHERE age>33 AND age<=40   $db->users->find(array(“age” => array(‘$gt’ => 33, ‘$lte’ => 40)));
SELECT * FROM users ORDER BY name DESC   $db->users->find()->sort(array(“name” => -1));
CREATE INDEX myindexname ON users(name)   $db->users->ensureIndex(array(“name” => 1));
CREATE INDEX myindexname ON users(name,ts DESC)   $db->users->ensureIndex(array(“name” => 1, “ts” => -1));
SELECT * FROM users WHERE a=1 and b=’q’   $db->users->find(array(“a” => 1, “b” => “q”));
SELECT * FROM users LIMIT 10 SKIP 20   $db->users->find()->limit(10)->skip(20);
SELECT * FROM users WHERE a=1 or b=2   $db->users->find(array(‘$or’ => array(array(“a” => 1), array(“b” => 2))));
SELECT * FROM users LIMIT 1   $db->users->find()->limit(1);
EXPLAIN SELECT * FROM users WHERE z=3   $db->users->find(array(“z” => 3))->explain()
SELECT DISTINCT last_name FROM users   $db->command(array(“distinct” => “users”, “key” => “last_name”));
SELECT COUNT(*y) FROM users   $db->users->count();
SELECT COUNT(*y) FROM users where AGE > 30   $db->users->find(array(“age” => array(‘$gt’ => 30)))->count();
SELECT COUNT(AGE) from users   $db->users->find(array(“age” => array(‘$exists’ => true)))->count();
UPDATE users SET a=1 WHERE b=’q’   $db->users->update(array(“b” => “q”), array(‘$set’ => array(“a” => 1)));
UPDATE users SET a=a+2 WHERE b=’q’   $db->users->update(array(“b” => “q”), array(‘$inc’ => array(“a” => 2)));
DELETE FROM users WHERE z=”abc”   $db->users->remove(array(“z” => “abc”));

This table is copied from http://php.net/manual/en/mongo.sqltomongo.php

comments powered by Disqus