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 :)