Getting Started with PHP and MongoDB®

3 min read
Getting Started with PHP and MongoDB®


ScaleGrid is a MongoDB® management solution for public clouds. MongoDB (from “humongous”) is a scalable, high-performance, open source NoSQL database by 10gen.

ScaleGrid will help you provision, configure high availability and disaster recovery, deprovision, monitor, upgrade, clone, backup and recover your MongoDB® deployments on AWS, Azure, and DigitalOcean. One of the advantages of ScaleGrid is that it gives you full SSH access to your instances. This enables you to run your PHP server on the same machine as your MongoDB server, an extremely useful benefit for dev and test scenarios. In this tutorial, we’ll show you in five simple steps how to setup your PHP server and MongoDB® server on the same machine.

Create your MongoDB® Instance on ScaleGrid

Follow the getting started directions here to create your machine pool, create MongoDB® instances, retrieve SSH credentials and SSH into the instance, or check out our Create a MongoDB Cluster documentation.

Connect to MongoDB® and Populate Your Data

SSH into your MongoDB® instance. Connect to your local MongoDB instance using the built-in mongo client and fire off some queries:

MongoDB shell version: 2.0.7
connecting to: test

> show dbs
config (empty)
local (empty)

> db.version()

> db.stats()
  "db" : "test",
  "collections" : 0,
  "objects" : 0,
  "avgObjSize" : 0,
  "dataSize" : 0,
  "storageSize" : 0,
  "numExtents" : 0,
  "indexes" : 0,
  "indexSize" : 0,
  "fileSize" : 0,
  "nsSizeMB" : 0,
  "ok" : 1

Let’s create a dummy database and insert some data into a collection. “Collections” are the equivalent of relational tables. A collection can contain many “documents” which is the equivalent of rows in the relational world.

> use testdb
switched to db testdb

> db.testcollection.insert({"name":"blah", "value":"humbug"});

> db.testcollection.insert({"name":"blah1", "value":"humbug1"});

> db.find();
{ "_id" : ObjectId("50db292013d7f5d141a9cbfb"), "name" : "blah", "value" : "humbug" }
{ "_id" : ObjectId("50db292913d7f5d141a9cbfc"), "name" : "blah1", "value" : "humbug1" }

Setup Your PHP Server

If you already have a PHP server running on a machine separate from your MongoDB® server, you can skip this step and move to step 4. If you don’t have a PHP server, you can install a PHP server on the MongoDB® machine. This is one of the benefits of having full SSH access to your MongoDB machines:

[root@ip-10-29-173-18 ~]# yum install httpd php
[root@ip-10-29-173-18 ~]# chkconfig httpd on
[root@ip-10-29-173-18 ~]# service httpd start

Install the Mongo PHP Extension

MongoDB® support in PHP is through the Mongo PHP extension. You can  install it using the PECL installer:

[root@ip-10-29-173-18 ~]# yum install php-pear
[root@ip-10-29-173-18 ~]# yum install php-devel
[root@ip-10-29-173-18 ~]# yum install make
[root@ip-10-29-173-18 ~]# pecl install mongo
[root@ip-10-29-173-18 ~]# echo "" >> /etc/php.ini
[root@ip-10-29-173-18 ~]# /etc/init.d/httpd restart

Run PHP Code

Retrieve the MongoDB connection string from the ScaleGrid console in the details tab at the bottom of the screen.  If you’re running your PHP code on the same box, you can use

Let’s write some PHP code to query the documents in the collection we just created. Create a file called test.php and put the code below into the file. Run the code using “php test.php”.

try {
  // Open connection to MongoDB server
  $conn = new Mongo('<connection string>');

  // Access the database
  $db = $conn->testdb;

  // Access the collection
  $collection = $db->testcollection;

  // Execute the query
  // Retrieve all documents
  $cursor = $collection->find();

  // Iterate through the result set
  // Print each document
  echo $cursor->count() . ' document(s) found.' . PHP_EOL;
  foreach ($cursor as $obj) {
    echo 'Name: ' . $obj['name'] . PHP_EOL;
    echo 'Value: ' . $obj['value'] . PHP_EOL;
    echo PHP_EOL;

  // Disconnect from the server
} catch (MongoConnectionException $e) {
  die('Error connecting to MongoDB server');
} catch (MongoException $e) {
  die('Error: ' . $e->getMessage());

For more detailed instructions and examples refer to the 10gen documentation on using PHP with MongoDB®.


For more information, please visit Connect with ScaleGrid on LinkedIn, X, Facebook, and YouTube.
Table of Contents

Stay Ahead with ScaleGrid Insights

Dive into the world of database management with our monthly newsletter. Get expert tips, in-depth articles, and the latest news, directly to your inbox.

Related Posts

Setting Up MongoDB SSL Encryption

In a world where data security is essential, enabling MongoDB SSL is critical in fortifying your database. This guide walks...

distributed storage system

What is a Distributed Storage System

A distributed storage system is foundational in today’s data-driven landscape, ensuring data spread over multiple servers is reliable, accessible, and...

MySQL Backups: Methods & Best Practices

Regarding MySQL backups, knowing how to secure your data is crucial. This guide cuts through the complexity, providing instructions on...


Add Headline Here