Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Sam Millman, an active participant on both the official MongoDB user group at mongodb-user and on Stackoverflow MongoDB.

PHP is an open source (git hosted) dynamic interpreted language for building web sites. With its ease of use and installation, PHP has become one of the leading web languages for new-comers and professionals alike. It is also one of my favorite languages. Despite its many flaws, it seems to fit with the Internet really well.

I have programmed in a wide range of languages including Java, Smalltalk, C++, C#, Visual Basic, QBASIC and various server-side JavaScript implementations. Despite this, however, PHP is one I keep coming back to for web development. Its simplicity and dynamic nature make it perfect for websites. As such, it is not surprising that my love for MongoDB would eventually be entwined with PHP. In this article, I’m going to walk you through the absolute basics of using the PHP driver and translating the MongoDB shell commands to their PHP equivalent.

Installing the MongoDB PHP driver

It isn’t good enough to just install MongoDB and PHP, you must also install a driver into your PHP installation in order for your application to be able to communicate with MongoDB. Read Chapter 2. PHP, MongoDB, and You in MongoDB and PHP to learn about installing MongoDB and PHP in various environments.

The driver is vital for allowing your application to communicate to MongoDB, and is commonly mistaken as already being installed. If you are unsure as to whether the PHP driver is installed or not, you can create a new file with a single line of phpinfo:

This will then echo out a page displaying a large amount of information about the current state of your PHP installation, including a section titled mongo. If this section exists, it means you have the driver successfully installed. If not, then please install the driver.

Connecting to MongoDB

The MongoClient class is used to connect to MongoDB from PHP. Let’s dive right in with a sample:

This is the most basic example of how to connect to a MongoDB instance running on the same computer as your PHP installation. The default setup of MongoClient is to try and connect to a MongoDB instance running on port 27017 of your current machine, otherwise known as localhost or

The line $db=$client->my_database; should have my_database replaced with your database name. Everything in MongoDB’s PHP driver is done by object accession (by default), so when you fetch back the $client and you call ->my_database, you are in fact using the magics of the MongoClient class to access a database.

Querying MongoDB

So now we have our database object ready to use in the $db variable, let’s do some querying.

Using the PHP driver is a lot like doing it within the console, except you just transfer it over to PHP sytnax. Let’s start with an example. In the console you would write:

This inserts a new document with a single field of name with a value of sammaye in the collection collection. It is much the same in PHP, as I will now demonstrate:

So, instead of a JavaScript notation to define objects, you simply use array() in place of them. PHP has no difference between an array [] and an object {}, so you only need to remember to replace all notations with a single one of array().

So, now for a more complex example, after reading another post here about basic MongoDB querying:

You will notice a few new things in this particular query. First, you see $or, which must be wrapped in literal quotes '' in order for PHP not to mistake it as a variable. Second, you will notice that I chain the methods of the query, which in SQL you would normally write out all in one line. This is due to how querying MongoDB works.

Whenever you use the find method in the PHP driver, it will in fact return an instance of a MongoCursor, which will allow you to build up your queries before actually querying. When you iterate for the first time, the cursor will shoot the query off to MongoDB and return a batch of results.

Using data types in MongoDB

So now we know how to query in MongoDB, but many ask themselves: “How do I query by ObjectId or Date or some other object?”

The first document you should read is about types in the PHP documentation, where examples and explanations are readily shown.

Most MongoDB types in PHP are used as objects, for example, to query by ISODate in PHP:

This will find all records within the collection collection, which have a date_created field whose ISODate value is equal to 2012-05-06 00:00:00.

Querying by the _id field is much the same. The key to understanding this is to remember that the ObjectId in PHP is actually a MongoId. So, to query for the _id field in PHP:


We explored and grasped how to connect to and query a MongoDB instance using PHP. We queried not only using strings and integers, but also by using data types such as the MongoId (ObjectId) and MongoDate (ISODate).

Safari Books Online has the content you need

Below are some MongoDB books with all sorts of tips and information.

MongoDB: The Definitive Guide, 2nd Edition shows you the many advantages of using document-oriented databases, and demonstrates how this reliable, high-performance system allows for almost infinite horizontal scalability.
MongoDB in Action is a comprehensive guide to MongoDB for application developers. The book begins by explaining what makes MongoDB unique and describing its ideal use cases. A series of tutorials designed for MongoDB mastery then leads into detailed examples for leveraging MongoDB in e-commerce, social networking, analytics, and other common applications.
MongoDB and Python is a cookbook-style text to help Python programmers work with MongoDB. It is full of useful, practical recipes for solving real-world problems ranging from how to do fast geo queries for location-based apps to efficiently indexing your user documents for social-graph lookups to how best to integrate MongoDB with the Pyramid Web framework.
Learn how to create large MongoDB clusters! Scaling MongoDB shows you how to use MongoDB efficiently for very large databases. It Covers sharding, cluster setup, and administration.

About the author

sammillman Sam Millman has been using MongoDB for almost 4 years now starting with MongoDB when it had just been released. He is an active participant on both the official MongoDB user group at mongodb-user and on Stackoverflow MongoDB. He has a love for all things web based and enjoys actively building web awesomeness in jQuery and PHP with a little Python on the side. You can contact him either at his blog as or on Twitter as @sam_millman.

Tags: Javascript, MongoDB, php, phpinfo, Query, SQL, web development,

Comments are closed.