Skip to main content

MongoDB with PHP – Configuration and Examples

So, in previous posts, we have seen What is MongoDB and how we can perform CRUD operation on MongoDB

So, moving ahead, lets learn how to use MongoDB with PHP. 

By default, PHP assumes you will be using MySQL, so till now it doesn’t support MongoDB. But we can add the Mongo DB support to our existing PHP.

On Windows

Go to the link, download the suitable version of zip. This zip contains the dll for mongo you will be using.
Just unzip the zip file, and select the appropriate version of the dll(for ex, if you are using php 5.3.13 and you have downloaded the  , on 32-bit systems, you needs to use the php_mongo-1.4.5-5.3-vc9.dll from the zip.  So select the appropriate version as per 32/ 64 bit and your PHP version.
Then just rename the dll file to php_mongo.dll and paste it to your php extensions directory.(ext by default).
Then open your php.ini file, add the line 

and restart your server. To verify, whether mongo is setup or not, just open localhost and cllck phpinfo() and search for “mongo” section. If its there, means you are done with configuration and you can move ahead to the coding part.

For  Linux users,  two commands needs to be run from terminal

sudo apt-get install php5-dev php5-cli php-pear 
sudo pecl install mongo  
Then in php.ini  file, add the line  

and restart your server. To verify, whether mongo is setup or not, just open localhost and cllck phpinfo() and search for “mongo” section. If its there, means you are done with configuration and you can move ahead to the coding part.

Once the configuration is done, lets get into the second part- examples.

Note : Before moving ahead make sure you have running MongoDB server(mongod)

         Creating a connection

$con = new MongoClient(); // connects to localhost:27017

If you want to connect to some remote host on 27017 port
$con = new MongoClient( "mongodb://" ); 

If you want to connect to some remote host on any port (say 34567)
$con = new MongoClient( "mongodb://" ); 

         Making the database connection(Say db name : learn and collection name :users)

$con = new MongoClient();

// Connecting to the database
$db = $connection->learn;

// Getting the Collection
$collection = $db->users;

c       Making database query

1 ) Insert Query
$query = array (
        'name' => 'ankit bansal',
        'age' => 24,
        'hobby' => 'music'
This will insert the document in collection users
2)  Select Query(find() and findOne())
Using findOne()

$document = $collection->findOne();
foreach ( $document as $key => $value )
                        echo $key. "=>" .$value. "<br />";           
As we know, findOne() returns a single doc, it can be iterate using foreach
Using find()
$cursor = $collection->find();
foreach ( $cursor as $key => $value )
        echo "********************************************************<br />";
        foreach ($value as $key1 =>$value1)
                        echo $key1. "=>" .$value1. "<br />";
As we know find returns an cursor, with lots of documents, it can be considered as an array of documents. So it cann be iterate using two nested foreach loops.

Using where clause in find()

$query = array('age' => 35);
$cursor = $collection->find($query);
foreach ( $cursor as $key => $value )
        echo "********************************************************<br />";
        foreach ($value as $key1 =>$value1)
                        echo $key1. "=>" .$value1. "<br />";

For the where clause(search based on condition), just create  the array for search and pass it to find().
To count the number of records returned,
$cursor = $collection->find($query)->count();

3) Update Query
$query = array(
        "age" => 23

$update = array(
                        '$set' => array(
                                                        "name" => "Ashish Gupta"


Note :  use $set with single quotes only not with double quotes as if double quotes are used, PHP will considered it as an PHP variable and will give the error.

4) Delete Query
$query = array(
                "age" => 23


That’s it.

If the above concept is clear, you can perform any task using MongoDB in PHP.

  Download the complete examples        

You can also check our Microservices post
Introduction to Microservices


Popular posts from this blog

Login with Google Account using PHP / Javascript using OAuth2.0

Login with Google Account using PHP with code
This post have Complete Code for Login / Sign-in  with google Account  using PHP / Javascript with oAuth2.0

Basically today we have seen almost every website needs you to register yourself before you can post or take part in any discussions to the website. But it become a tedious task to register and login to many different sites. Solution is to provide the users the option to Login with existing Google / Facebook account as almost everyone have Facebook and Google account..

In this post, I am going to explain how to integrate the Google Login / Sign in  for your website.

For this,  First you need to create your Client ID, Client Secret and your developer API key.

For this go to

Click on the button Create Project. A new window will open up. Please select Create Project / or select already created Project.

It will then ask for about type of Project. Please select Web-browser. Then it …

What is MonGoDB??

Share on Google Plus Now a Days, we are hearing a lot about MongoDB.

So, in this post I will try to briefly introduce to MongoDB.

MonGoDB is "Non-Relational, JSON, Document Store".

Explaining in detail,

Non-Relational, --> The DB we use most like SQl, Oracle are Relational DBs(RDBMS). They do have the fixed schemas, lots of tables. So Non-relational in nothing like that.

JSON : (JavaScript Object Notation) : It is basically a document with information in the form of key value pair.

for example,


thats it. 
A simple JSON document where name and address are key
and "lorem" and "ipsum" are corresponding values.

So, MongoDB is the Non Relational database which stores information using DOCUMENT and that document is a JSON document.

MongoDB stores collections of documents.
(Consider the above exxample as collection  "Person"  with a document)(will elaborate it later more)

Need of MongoDB:
The Databases we use…

TCP Chat Server in Node.js

d.Hello all.

Today in this post, I am going to explain about how to use a "net" module in node.js and build a basic chat server.(i.e a TCP chat server)

For this, you need to use either telnet / netcat(nc).(I have tried it on netcat, simply google "netcat download")
(Dont worry about the script for now, i will upload it, just go through the tutorial to understand the concept)

So, lets begin,

first of all to use node "net" module , we need to import it in out script.

var net = require("net")

This will import the net module. Now moving ahead, we need to create a server. This is done by createServer  function(on simply Server function).

var server = net.createServer()

createServer has a callback whenever a client connects to a server.

var server = net.createServer(function(socket){


The code inside the createServer() function is callback(Hope you have know about the callbacks / event driven programming). This gets called whenever, a client gets c…