MongoDB - PHP
Modern MongoDB with PHP
Section titled “Modern MongoDB with PHP”**Important Note:** This tutorial has been completely rewritten to use the modern MongoDB PHP Driver. The old `mongo` extension and `MongoClient` class are deprecated and have been removed from recent PHP versions. All new projects must use the `mongodb` extension and the official Composer library.1. Setting Up Your Environment
Section titled “1. Setting Up Your Environment”Modern PHP development with MongoDB relies on two components:
- The PHP Extension (
mongodb): A low-level driver installed via PECL that handles the binary communication with the database. You’ll need to addextension=mongodb.so(or.dllon Windows) to yourphp.ini. - The PHP Library (
mongodb/mongodb): A high-level, user-friendly library installed via Composer. This is what you will interact with in your code.
First, create a project directory and initialize Composer. Then, require the MongoDB library:
mkdir php-mongo-projectcd php-mongo-projectcomposer require mongodb/mongodbThis will install the library and create a vendor/autoload.php file, which you must include in your scripts.
2. Making a Connection
Section titled “2. Making a Connection”Create a PHP file (e.g., index.php) and include the Composer autoloader. Then, instantiate the MongoDB\Client class with your connection string URI.
<?phprequire_once __DIR__ . '/vendor/autoload.php';
// Connection URI. For production, use environment variables!$uri = 'mongodb://localhost:27017';
try { // Create a new client and connect to the server $client = new MongoDB\Client($uri);
// Select a database and collection $database = $client->selectDatabase('myAppDb'); $collection = $database->selectCollection('users');
echo "Connection to database successful!\n"; // You can also select the database and collection with magic properties: // $collection = $client->myAppDb->users;
} catch (Exception $e) { printf("Could not connect to MongoDB: %s\n", $e->getMessage());}3. CRUD Operations
Section titled “3. CRUD Operations”Let’s perform the basic Create, Read, Update, and Delete operations.
Insert a Document (insertOne)
Section titled “Insert a Document (insertOne)”<?php// ... (connection code from above)
$insertOneResult = $collection->insertOne([ 'username' => 'johndoe', 'email' => 'john.doe@example.com', 'registered_at' => new MongoDB\BSON\UTCDateTime(),]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());var_dump($insertOneResult->getInsertedId());Find a Document (findOne)
Section titled “Find a Document (findOne)”<?php// ... (connection code from above)
$document = $collection->findOne(['username' => 'johndoe']);
if ($document) { echo "Found user: " . $document['username'] . "\n"; var_dump($document);} else { echo "User not found.\n";}Find Multiple Documents (find)
Section titled “Find Multiple Documents (find)”The find() method returns a cursor, which you can iterate over.
<?php// ... (connection code from above)
// Find all documents. For production, always use filters and projections!$cursor = $collection->find([], [ 'sort' => ['registered_at' => -1], // Sort by newest first 'limit' => 10,]);
foreach ($cursor as $doc) { printf("User: %s, Email: %s\n", $doc['username'], $doc['email']);}Update a Document (updateOne)
Section titled “Update a Document (updateOne)”<?php// ... (connection code from above)
$updateResult = $collection->updateOne( ['username' => 'johndoe'], ['$set' => ['status' => 'active']]);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());printf("Modified %d document(s)\n", $updateResult->getModifiedCount());Delete a Document (deleteOne)
Section titled “Delete a Document (deleteOne)”<?php// ... (connection code from above)
$deleteResult = $collection->deleteOne(['username' => 'johndoe']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());Project Best Practices
Section titled “Project Best Practices”- Error Handling: Always wrap your database logic in
try...catchblocks to handle exceptions gracefully. - Configuration: Never hard-code connection strings. Use environment variables (e.g., via a
.envfile and a library likevlucas/phpdotenv) to manage configuration. - Data Types: Use the BSON classes provided by the library (e.g.,
MongoDB\BSON\UTCDateTime,MongoDB\BSON\ObjectId) to ensure data is stored correctly. - Advanced Topic (ODMs): For larger applications, consider using an Object-Document Mapper (ODM) like Doctrine MongoDB ODM, which allows you to work with PHP objects that map to MongoDB documents, simplifying complex data logic.