MongoDB is an open-source leading NoSql database. In my previous posts , I explain the MongoDB terminology, installation process,creating and quering DB. In this article i will explain how to install and connect MongoDB with PHP.
Let’s quickly go through the popular terminology used in MongoDB
Database – In RDBMS database is a collection of tables. In Mongo Database is a set of collections.
Collections – Collection in mongodb is like a table in mysql. But it does not have schema. It is a schema-less.
Document – It is like a record or row in relational databases (like mysql). It is stored in BSON (Binary Json) format.
How to Install and Create Database with MongoDB
Installing MongoDB Driver for PHP
I assume you have already installed LAMP (for linux users) on your system.
Installed some dependency
1 |
sudo apt-get install php-pear php5-dev |
To install Mongodriver for PHP
1 |
sudo pecl install mongo |
After installing mongodriver, you need to add extension = mongo.so in your php.ini file.
1 |
sudo vi /etc/php5/apache/php.ini |
After adding extension in php.ini file. Restart the Apache server.
To restart, type
1 |
sudo /etc/init.d/apache2 restart |
To check MongoDB driver installation, use
1 |
phpinfo(); |
Now we have installed MongoDB driver for PHP. Let’s write some PHP code for connecting to MongoDB.
MongoDB Installation Guide for Windows User
Connect with PHP
I am using bookmarks DB which i already created. Now i am accessing the records of emp collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// creating connection object $connection = new Mongo(); // Using bookmarks DB $db = $connection->bookmarks; // emp collection $collection = $db->emp; // Accessing only one record of emp collection $obj = $collection->findOne(); // findOne is similar to limit 1 (in MySql) var_dump($obj); |
Add Collection
Creating connection object.
1 |
$connection = new Mongo(); |
Use bookmarks database.
1 |
$db = $connection->bookmarks; |
creating new collection product under bookmarks database.
1 |
$collection = $db->products; |
Make product array for insertion.
1 2 3 4 5 6 |
$product = array( 'name' => 'samsung', 'qty' => 100, 'price' => 10000, 'desc' => 'LED Tv' ); |
Insert the Value
1 |
$collection->insert( $product ); |
To check the inserted record open terminal
1 2 3 4 5 6 7 8 9 10 11 |
// To start mongo shell on terminal mongo // Switch to bookmarks DB use bookmarks; // print the record of products table db.products.find(); |
Conclusion
Hope this article is helpful, for installation and creating MongoDB connection to PHP.