Skip to main content
MongoDB
CHAPTER 23 Beginner

Connecting MongoDB with PHP

Updated: May 16, 2026
15 min read

# CHAPTER 23

Connecting MongoDB with PHP

1. Introduction

A database without an application is useless. To make our MongoDB database interact with the real world, we must connect it to a backend web server. PHP is a foundational backend language, powering heavily trafficked CMS platforms like WordPress and Laravel applications. In this chapter, we will bridge the gap between software engineering and database administration by securely connecting PHP to MongoDB.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the architecture of the MongoDB PHP Driver vs. the PHP Library.
  • Install the MongoDB Library using Composer.
  • Establish a secure database connection.
  • Execute basic CRUD operations (Insert, Find, Update, Delete) using PHP arrays.
  • Handle connection exceptions gracefully.

3. Driver vs. Library Architecture

Connecting PHP to MongoDB requires two components:
  1. 1. The PHP Extension (The Driver): A low-level C extension installed on the server (e.g., via pecl install mongodb). It handles the raw binary network communication.
  1. 2. The PHP Library: A high-level Composer package written in PHP. It provides the clean, object-oriented API that developers actually write code against.

*Always ensure your server administrator has installed the mongodb PHP extension before proceeding!*

4. Installing the PHP Library

In your PHP project directory, use Composer to install the official library:
bash
1
composer require mongodb/mongodb

5. Establishing the Connection

To connect, we instantiate the MongoDB\Client class, passing our secure Connection String URI (from Chapter 20).
php
1234567891011121314151617181920212223
<?php
// Require the Composer autoloader
require &#039;vendor/autoload.php';

// The Secure URI (Use an environment variable in production!)
$uri = "mongodb+srv://webapp_user:WebAppPassword99!@cluster0.xyz.mongodb.net/";

try {
    // 1. Create the Client Connection
    $client = new MongoDB\Client($uri);
    
    // 2. Select the Database
    $database = $client->ecommerce_db;
    
    // 3. Select the Collection
    $collection = $database->users;
    
    echo "Successfully connected to MongoDB!";
} catch (Exception $e) {
    // Gracefully catch network errors
    die("Connection failed: " . $e->getMessage());
}
?>

6. Executing CRUD: Create (insertOne)

In PHP, JSON objects are represented by Associative Arrays.
php
1234567891011
<?php
$insertResult = $collection->insertOne([
    &#039;first_name' => 'Alice',
    &#039;email' => 'alice@example.com',
    &#039;age' => 28,
    &#039;skills' => ['PHP', 'MongoDB'] // Arrays map perfectly to BSON arrays!
]);

// Retrieve the automatically generated ObjectId
printf("Inserted 1 document with ID: %s", $insertResult->getInsertedId());
?>

7. Executing CRUD: Read (find and findOne)

To query data, we pass an associative array as the filter document.
php
123456789101112131415
<?php
// Find a single user
$user = $collection->findOne([&#039;email' => 'alice@example.com']);
echo "Welcome back, " . $user[&#039;first_name'] . "<br>";

// Find multiple users (Returns a Cursor)
// Using Operators requires wrapping the operator in quotes!
$cursor = $collection->find([
    &#039;age' => ['$gte' => 21] // Find users >= 21
]);

foreach ($cursor as $document) {
    echo $document[&#039;first_name'] . "\n";
}
?>

8. Executing CRUD: Update and Delete

Notice how the syntax maps almost identically to the mongosh terminal commands!
php
123456789101112
<?php
// Update (Remember the $set operator!)
$updateResult = $collection->updateOne(
    [&#039;email' => 'alice@example.com'],
    [&#039;$set' => ['status' => 'Premium']]
);
echo "Modified " . $updateResult->getModifiedCount() . " documents.<br>";

// Delete
$deleteResult = $collection->deleteOne([&#039;email' => 'alice@example.com']);
echo "Deleted " . $deleteResult->getDeletedCount() . " documents.";
?>

9. Common Mistakes

  • Exposing Credentials: Never hardcode $uri = "mongodb+srv://admin:pass..." directly in your PHP files if you are pushing code to GitHub. Always use a library like vlucas/phpdotenv to load the URI from a secure .env file that is excluded from version control!
  • Not Using ObjectIds correctly: If you receive an ID string from a URL (e.g., edit.php?id=650a2...), you cannot query findOne(['_id' => $idString]). You MUST convert the string into a true BSON ObjectId object first:
new MongoDB\BSON\ObjectId($idString).

10. Best Practices

  • Singleton Connection: Opening a network connection to MongoDB takes time. If your PHP app opens a new new MongoDB\Client() connection in 5 different files during a single page load, the site will be incredibly slow. Use a Singleton class or Dependency Injection to ensure the connection is opened exactly once per request.

11. Exercises

  1. 1. What PHP data structure is used to represent a MongoDB JSON/BSON document?
  1. 2. Write the PHP code to convert a standard string $myStringId = "507f1f77bcf86cd799439011" into a queryable MongoDB ObjectId.

12. MongoDB Challenges

Write the PHP code to execute an updateMany() command on the $collection, using the $inc operator to add 100 to the loyalty_points of every document where status is 'VIP'.
php
1234
$collection->updateMany(
    [&#039;status' => 'VIP'],
    [&#039;$inc' => ['loyalty_points' => 100]]
);

13. MCQ Quiz with Answers

Question 1

When interacting with MongoDB via PHP, how do you specify advanced query operators like $gt or $set?

Question 2

Why must the Connection String URI in a PHP application be stored in an Environment Variable (.env file) rather than hardcoded in the script?

14. Interview Questions

  • Q: Explain the architectural difference between the low-level MongoDB PHP extension (Driver) and the high-level Composer Library. Why are both required?
  • Q: In traditional SQL/PHP applications, "SQL Injection" is a massive threat. How does MongoDB's use of BSON and Associative Arrays inherently mitigate traditional SQL injection vectors?

15. FAQs

Q: Can I use MongoDB with the Laravel Framework? A: Absolutely! While Laravel defaults to SQL, the community maintains a massive package called jenssegers/mongodb (now transitioned to mongodb/laravel-mongodb) which allows you to use Laravel's elegant Eloquent ORM seamlessly with MongoDB!

16. Summary

You have successfully bridged the gap between the application server and the database. By utilizing the official MongoDB PHP Library, handling associative arrays, and securely managing your connections, you guarantee a high-performance data pipeline between PHP and NoSQL.

17. Next Chapter Recommendation

PHP is fantastic, but MongoDB uses JSON. What if we could use a backend language that speaks JSON natively? In Chapter 24: Connecting MongoDB with Node.js, we will explore the MERN stack architecture, connecting MongoDB to its native language: JavaScript.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·