How to connect to MongoDB using PHP

Josh Sherman
1 min read
Software Development PHP NoSQL

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

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles