How To Configure And Connect MongoDB And Php On Ubuntu

Am starting the tutorial hoping that you have already set up php using lamp stack. If not install lamp server using the following command
sudo apt-get install lamp-server^

Installing MongoDB :

Step 1: Execute the following command

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10

Step 2: Create a file called 10gen.list and add “deb http://downloads-tro.mongodb.org/repo/ubuntu-upstart dist 10gen ” line as shown below. save the file before exiting.

 cd /etc/apt/sources.list.d
sudo nano 10gen.list

Step 3: Now update the repository and install mongodb using the following commands.

sudo apt-get update
sudo apt-get install mongodb-10gen

Step 4: Mongodb will be installed after successfull execution of above command. You can start creatinf databases and collections using the terminal. You just have to type mongo in the terminal window. MongoDb will be automatically connected. You can check the following link to get started with mongoDB. Getting Started With MongoDB

Connecting PhP and MongoDB:

Inorder to connect php and mongoDB you have to install php driver for mongoDB.

Step 1:Execute the following commands in terminal to install the php driver for mongoDB.

sudo apt-get install php5-dev php5-cli php-pear
sudo pecl install mongo

Step 2:Add extension=mongo.so to the php.ini file. Use the following commands to locate and edit the php.ini file

cd  /etc/php5/apache2 
sudo nano php.ini

Step  3: You can use the following php script to connect to mongoDB.

<?php

$m = new Mongo();

$db = $m->selectDB("comtechies");

$db->createCollection(“users”,false);

?>
0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like