Introduction

If you want to create a website using MongoDB and PHP, this article will help you to:

  • Connect to a MongoDB database
  • Save documents in a collection
  • Query documents in a collection
  • Perform range queries
  • Sort documents, update a document, delete one or more documents from a collection

What is MongoDB ?

MongoDB is a NoSQL cross-platform document-oriented database. It is one of the most popular databases available. MongoDB is developed by MongoDB Inc. and is published as free and open-source software.

A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents. MongoDB stores documents in collections. Collections are analogous to tables in relational databases and documents to rows.

MongoDB Concepts: Databases, Collections, and Documents

  1. Database: MongoDB groups data into databases in the very same way as most relational databases do. If you have any experience with relational databases, you should think of these the same way. In an RDBMS, a database is a set of tables, stored procedures, views, and so on. In MongoDB, a database is a set of collections. A MongoDB database contains one or more collections. For example, a database for a blogging application named blog may typically have the collections articles, authors, comments, categories, and so on.
  2. Collection: A collection is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection have a similar or related purpose.
  3. Documents: A record in a MongoDB collection and the basic unit of data in MongoDB. Documents are analogous to JSON objects but exist in the database in a more type-rich format known as BSON. A document contains a set of fields or key-value pairs. The best way to think of a document is as a multidimensional array. In an array, you have a set of keys that map to values (Document == Array). See Documents.

Installing MongoDB

MongoDB runs on most platforms and supports 32-bit and 64-bit architectures. MongoDB is available as a binary, or as a package. In production environments, use 64-bit MongoDB binaries. This section will cover installation on Ubuntu Linux and Windows. For other operating systems, please see their documentation.

This is how Mongo is installed on Ubuntu Linux. Open terminal and execute the following:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
#
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Now issue the following command to update your repository and install the latest stable version of MongoDB:

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

Done, you have successfully installed MongoDB. Now start and stop service MongoDB via command line below.

sudo service mongodb start
sudo service mongodb stop

In case of start error to try run the following command:

sudo mongod --fork --logpath /var/log/mongodb/mongodb.log
#or
sudo mongod -f /etc/mongodb.conf

The following describes how to install it on Windows:

Head on over to the downloads page on the MongoDB official website. Click on the download link for the latest stable release under Windows.

After the download is finished, extract and move it into C:\ . MongoDB requires a data folder in which to store its files. The default location for the MongoDB data directory is C:\data\db. If it doesn’t exist, create it.

To start MongoDB, execute from the Command Prompt

C:\> cd \mongodb\bin
C:\mongodb\bin> mongod

Done, you have successfully installed MongoDB. Now start and stop service MongoDB via command line below.

net start MongoDB
net stop  MongoDB

Installing the PHP driver for MongoDB

The MongoDB server is built to already work with your current web server, but not PHP. To make PHP talk to the MongoDB server, we are going to need the PHP-MongoDB driver. It is a PHP extension library.

If you use Linux install it easily via:

sudo pecl install mongo

Add the line extension=mongo.so to your php.ini configuration and you’re good to go:

sudo -i
echo 'extension=mongo.so' >> /etc/php5/apache2/php.ini

Restart your web server and verify via command line:

php -i |grep "mongo"
php --re mongo

Installing the Driver on Windows

Let us try installing the driver on a Windows machine running PHP 5.4 on Apache (XAMPP):

  1. Download the ZIP archive https://github.com/mongodb/mongo-php-driver/downloads on your machine and extract it.
  2. Copy the php_mongo.dll file from the extracted folder to the PHP extension directory(C:\xampp\php\ext).
  3. Open the php.ini file inside your PHP installation and add the following line: extension=php_mongo.dll
  4. Save the file and close it. Restart the XAMP.
  5. Open up your text editor and add the following code to a new file:<?php phpinfo();?>, save the file as phpinfo.php inside the DocumentRoot of the Apache web server (htdocs) and open the PHP script in the browser. If you see mongo in the PHP info, the installation was successful.

Advantages of MongoDB over RDBMS

  • Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another.
  • Structure of a single object is clear.
  • No complex joins.
  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that’s nearly as powerful as SQL.
  • Tuning.
  • Ease of scale-out − MongoDB is easy to scale.
  • Conversion/mapping of application objects to database objects not needed.
  • Uses internal memory for storing the (windowed) working set, enabling faster access of data.

Why Use MongoDB?

  • Document Oriented Storage − Data is stored in the form of JSON style documents.
  • Index on any attribute
  • Replication and high availability
  • Auto-sharding
  • Rich queries
  • Fast in-place updates
  • Professional support by MongoDB

Where to Use MongoDB?

  • Big Data
  • Content Management and Delivery
  • Mobile and Social Infrastructure
  • User Data Management
  • Data Hub

Create Database

MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn’t exist, otherwise it will return the existing database.

Syntax

Basic syntax of use DATABASE statement is as follows −

use DATABASE_NAME

Example

If you want to create a database with name <mydb>, then use DATABASE statement would be as follows −

>use mydb
switched to db mydb

To check your currently selected database, use the command db

>db
mydb

If you want to check your databases list, use the command show dbs.

>show dbs
local     0.78125GB
test      0.23012GB

Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it.

>db.movie.insert({"name":"tutorials point"})
>show dbs
local      0.78125GB
mydb       0.23012GB
test       0.23012GB

In MongoDB default database is test. If you didn’t create any database, then collections will be stored in test database.

Drop Database

The dropDatabase() Method

MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax

Basic syntax of dropDatabase() command is as follows −

db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will delete default ‘test’ database.

Example

First, check the list of available databases by using the command, show dbs.

>show dbs
local      0.78125GB
mydb       0.23012GB
test       0.23012GB
>

If you want to delete new database <mydb>, then dropDatabase() command would be as follows −

>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>

Now check list of databases.

>show dbs
local      0.78125GB
test       0.23012GB
>

Mongo Web Development with PHP

Connecting to a MongoDB Database Server

Connecting to MongoDB from PHP is very similar to connecting to any other database. The default host is localhost, and the default port is 27017.

$connection = new Mongo();

Connecting to a remote host with optional custom port and auth:

$connecting_string =  sprintf('mongodb://%s:%d/%s', $hosts, $port,$database),
$connection=  new Mongo($connecting_string,array('username'=>$username,'password'=>$password));

Selecting a Database

Once the database server connection is established, we will use it to access a database. The defined way to do this is:

$dbname = $connection->selectDB('dbname');

The Basics (CRUD Operations)

MongoDB provides rich semantics for reading and manipulating data. CRUD stands for create, read, update, and delete. These terms are the foundation for all interactions with the database.

Creating/Selecting a Collection

Selecting and creating a collection is very similar to accessing and creating a database. If a collection does not exist, it is created:

$collection = $dbname->collection;
//or
$collection = $dbname->selectCollection('collection');

For example, this creates the collection “posts” in my blog:

$posts = $dbname->posts

Creating a Document

Creating a document in MongoDB could not be easier. Create an array. Pass it into the insert method on the collection object

$post = array(
        'title'     => 'What is MongoDB',
        'content'   => 'MongoDB is a document database that provides high performance...',
        'saved_at'  => new MongoDate() 
    );
    $posts->insert($post);

The insert() method stores the data in the collection. The $post array automatically receives a field named _id, which is the autogenerated unique ObjectId of the inserted BSON document. You could also use the save() method, which upserts – updates an existing record, or creates a new one if it doesn’t exist.

Reading a Document

To get data from a collection, I use the find() method, which gets all the data in a collection. findOne() returns only one document that satisfies the specified query criteria. The following examples will show you how to query one or more records.

    // all records
    $result = $posts::find();
    // one record
    $id = '52d68c93cf5dc944128b4567';
    $results = $posts::findOne(array('_id' => new MongoId($id)));

Updating a Document

Modifies an existing document or documents in a collection. By default, the update() method updates a single document. If the multi option is set to true, the method updates all documents that match the query criteria.

    $id = '52d68c93cf5dc944128b4567';
    $posts->update(
                   array('_id' => new MongoId($id)),
                   array('$set'=> array(title'   => 'What is phalcon'))
                  );

The update() method takes two parameters. The first is criteria to describe the objects to update and the second the object with which to update the matching records. There is also a third optional parameter whereby you can pass in an array of options.

Conclusion

In this article, we covered a basic CRUD introduction into PHP with MongoDB. Now you could use MongoDB as an alternative to MySQL for your next PHP application. Happy coding folks 🙂

Summary
Article Name
MongoDB for PHP Developers - A Beginner's Guide
Description
Connecting to MongoDB from PHP is very similar to connecting to any other database. The default host is localhost, and the default port is 27017.
Author

Comments


Introduction If you want to create a website using MongoDB and PHP, this article will help you to: Connect...

Read Post

Leave a Reply

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