Php MongoDB

Php provides mongodb driver to connect with mongoDB database. After installing it, we can perform database operations by using the php. Here, we are using Ubuntu 16.04 to create an example. This example includes the following steps.

1) Installing Driver

snippet
$ pecl install mongodb
MongoDB Php mongodb connectivity 1

2) Edit php.ini File

It is store in the apache server directory /etc/php/7.0/apache2/php.ini

snippet
$ extension = mongodb.so
MongoDB Php mongodb connectivity 2

3) Install mongo-php library

Following is the preferred way of installing this library with Composer.

snippet
$ composer require mongodb/mongodb
MongoDB Php mongodb connectivity 4

4) Create Php Script

// connect.php

snippet
<?php
require 'vendor/autoload.php';
// Creating Connection
$con = new MongoDB\Client("mongodb://localhost:27017");
// Creating Database
$db = $con->rookienerd;
// Creating Document
$collection = $db->employee;
// Insering Record
$collection->insertOne( [ 'name' =>'Peter', 'email' =>'peter@abc.com' ] );
// Fetching Record
$record = $collection->find( [ 'name' =>'Peter'] );
foreach ($record as $employe) {
echo $employe['name'], ': ', $employe['email']."<br>";
}
?>

5) Execute Php Script

Execute this script on the localhost server. It will create database and store data into the mongodb.

snippet
localhost/php/connect.php
MongoDB Php mongodb connectivity 5

6) Enter into Mongo Shell

After executing php script, we can see the created database in mongodb.

snippet
$ mongo
MongoDB Php mongodb connectivity 6

6.1. Show Database

The following command is used to show databases.

snippet
> show dbs
MongoDB Php mongodb connectivity 7

6.2. Show Collection

The following command is used to show collections.

snippet
> show collections
MongoDB Php mongodb connectivity 8

6.3. Access Records

snippet
> db.employee.find()
MongoDB Php mongodb connectivity 9

Well all set, this is working fine. We can also perform other database operations as well.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +