Skip to content

MongoDB - 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.

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 add extension=mongodb.so (or .dll on Windows) to your php.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-project
cd php-mongo-project
composer require mongodb/mongodb

This will install the library and create a vendor/autoload.php file, which you must include in your scripts.

Create a PHP file (e.g., index.php) and include the Composer autoloader. Then, instantiate the MongoDB\Client class with your connection string URI.

<?php
require_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());
}

Let’s perform the basic Create, Read, Update, and Delete operations.

<?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());
<?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";
}

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']);
}
<?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());
<?php
// ... (connection code from above)
$deleteResult = $collection->deleteOne(['username' => 'johndoe']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
  • Error Handling: Always wrap your database logic in try...catch blocks to handle exceptions gracefully.
  • Configuration: Never hard-code connection strings. Use environment variables (e.g., via a .env file and a library like vlucas/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.