How to connect to MongoDB using PHP

I’ve previously discussed installing the MongoDB module but have yet
to touch on how to actually do anything past the install. The first thing to do
is to connect to the MongoDB server. This can simply be done like this:

$client = new MongoClient

This will connect to the default server (localhost) and port (27017). If you
want to connect to a different server or port you can use the same command and
pass the class the server string:

$client = new MongoClient('mongodb://remoteServer:31337'

Once connected, you probably want to select a database to work with. With the
way the MongoDB extension works you will simply reference the database as if it
were an object property:

$db = $mongo->myDatabaseName

And subsequently, the collection:

$collection = $db->myCollectionName

At this point you are able to interact with the collection to insert new
records and find records in the collection.

Next week we’ll discuss interacting with a MongoDB collection 🙂

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.