Paramclasses Academy - Blog

Tutorials Details

←
Post 27 of 35
→

MongoDB with PHP Using PHP Library: Complete Tutorial

MongoDB with PHP Using PHP Library: Complete Tutorial

November 6, 2026

MongoDB with PHP: Connect and Perform CRUD Operations

Introduction

PHP is a popular server-side programming language used to build dynamic websites, web applications, content management systems and backend services.

MongoDB is a NoSQL database that stores information in flexible, JSON-like documents. By connecting PHP with MongoDB, developers can build applications that store, retrieve, update and delete data efficiently.

To work with MongoDB in PHP, we use the official MongoDB PHP Driver and MongoDB PHP Library.

In this tutorial, you will learn how to install the required packages, connect PHP to MongoDB, create a database and collection, insert documents, retrieve records, update existing data and delete documents using practical examples.

1. What Is the MongoDB PHP Library?

The MongoDB PHP Library provides a high-level API that allows PHP applications to communicate with MongoDB databases.

The PHP integration has two important components:

  1. MongoDB PHP Extension: Provides the lower-level driver functionality required to communicate with MongoDB.

  2. MongoDB PHP Library: Provides convenient PHP classes and methods for working with clients, databases, collections and CRUD operations.

The official library is installed using Composer.

Important: Do not use the old MongoClient class from outdated PHP MongoDB tutorials. This tutorial uses the modern MongoDB\Client class.

2. Requirements Before Starting

Before connecting PHP with MongoDB, make sure you have:

  • PHP 7.4 or later, with a compatible MongoDB extension and library version.

  • Composer installed.

  • MongoDB Community Server or a MongoDB Atlas account.

  • Visual Studio Code or another PHP code editor.

  • Basic knowledge of PHP and MongoDB.

If you are using XAMPP, make sure the PHP version used by your command line and Apache is compatible with the MongoDB extension.

3. Install the MongoDB PHP Extension

The MongoDB PHP Extension is required before installing and using the high-level PHP Library.

First, check your PHP version:

php -v

Check whether the MongoDB extension is already installed:

php -m

Look for:

mongodb

If it does not appear, install the extension using the appropriate method for your PHP environment.

For supported environments with PIE, you can run:

pie install mongodb/mongodb-extension

You can also install a compatible extension through PECL:

pecl install mongodb

If You Are Using XAMPP on Windows

  1. Open your XAMPP installation folder.

  2. Check your PHP version using php -v.

  3. Download the matching MongoDB PHP extension DLL from the official PECL Windows downloads.

  4. Select a DLL compatible with your PHP version, architecture and thread-safety configuration.

  5. Copy the DLL into the PHP ext directory.

  6. Open the php.ini file used by your XAMPP installation.

  7. Add this line:

extension=mongodb
  1. Save the file.

  2. Restart Apache from the XAMPP Control Panel.

  3. Run php -m again to verify the extension.

Important: The PHP CLI and Apache can load different php.ini files. Check both environments if the extension appears in one but not the other.

4. Install the MongoDB PHP Library Using Composer

Create a project folder named:

mongodb_php_project

Open the terminal inside this folder.

Run:

composer require mongodb/mongodb

Composer downloads the MongoDB PHP Library and its dependencies.

After installation, your project structure will look similar to this:

mongodb_php_project/
│
├── vendor/
│   └── autoload.php
│
├── composer.json
├── composer.lock
└── index.php

The vendor folder contains the installed packages.

The vendor/autoload.php file loads the Composer dependencies into your PHP application.

5. Connect PHP to MongoDB

There are two common ways to connect PHP with MongoDB:

  • Local MongoDB Server

  • MongoDB Atlas Cloud Database

Option A: Connect to Local MongoDB

If MongoDB Community Server is installed and running on your computer, use:

mongodb://127.0.0.1:27017/

The default MongoDB port is 27017.

Option B: Connect to MongoDB Atlas

If you are using MongoDB Atlas, copy the connection string from your Atlas cluster.

It looks similar to:

mongodb+srv://<username>:<password>@cluster-name.mongodb.net/

Replace the placeholders with your actual database username, password and cluster address.

Before connecting, make sure:

  • A database user has been created.

  • Your current IP address is allowed in Atlas Network Access.

  • The user has the required database permissions.

  • Special characters in credentials are properly URL-encoded when included in the URI.

6. Create a PHP Connection File

Create a file named:

index.php

Add the following code:

<?php

require_once __DIR__ . '/vendor/autoload.php';

use MongoDB\Client;

try {

    // MongoDB connection string
    $uri = getenv('MONGODB_URI')
        ?: 'mongodb://127.0.0.1:27017/';

    // Create MongoDB client
    $client = new Client($uri);

    // Test MongoDB connection
    $client->selectDatabase('admin')->command(['ping' => 1]);

    echo "MongoDB connected successfully!";

} catch (Throwable $e) {

    echo "MongoDB connection failed: "
        . htmlspecialchars($e->getMessage());

}

Code Explanation

  • require_once loads the Composer autoloader.

  • use MongoDB\Client imports the MongoDB Client class.

  • getenv('MONGODB_URI') reads the connection string from an environment variable.

  • new Client($uri) creates a MongoDB client.

  • selectDatabase('admin') selects the admin database for the connection test.

  • command(['ping' => 1]) checks whether the MongoDB server responds.

  • catch handles connection or runtime errors.

For local development, the code uses the local MongoDB URI if the environment variable is not configured.

For production, store your MongoDB URI securely in the server environment. Do not publish database credentials in source code.

7. Create a Database and Collection

In MongoDB, a database contains collections, and collections contain documents.

Let's create the following database and collection:

  • Database Name: collegeDB

  • Collection Name: students

Add this code after creating the client:

$database = $client->selectDatabase('collegeDB');

$students = $database->selectCollection('students');

Explanation

  • selectDatabase() selects the database named collegeDB.

  • selectCollection() selects the students collection.

MongoDB creates the database and collection when data is first stored in them. Selecting them alone does not necessarily create them physically.

8. Insert One Document Using insertOne()

The insertOne() method inserts a single document into a MongoDB collection.

Example:

$student = [
    'name' => 'Rahul',
    'age' => 22,
    'course' => 'PHP',
    'city' => 'Raipur'
];

$result = $students->insertOne($student);

echo "Inserted ID: " . $result->getInsertedId();

Explanation

  • $student is a PHP associative array containing student details.

  • insertOne() inserts the document into the collection.

  • getInsertedId() returns the unique ID of the inserted document.

MongoDB automatically generates an _id field if you do not provide one.

Example Document:

{
    _id: ObjectId("..."),
    name: "Rahul",
    age: 22,
    course: "PHP",
    city: "Raipur"
}

The actual ObjectId will be generated by MongoDB and will be different for each inserted document.

9. Insert Multiple Documents Using insertMany()

The insertMany() method inserts multiple documents into a collection.

Example:

$studentsData = [
    [
        'name' => 'Amit',
        'age' => 21,
        'course' => 'Python',
        'city' => 'Raipur'
    ],
    [
        'name' => 'Priya',
        'age' => 23,
        'course' => 'Java',
        'city' => 'Bilaspur'
    ],
    [
        'name' => 'Rohit',
        'age' => 22,
        'course' => 'MongoDB',
        'city' => 'Durg'
    ]
];

$result = $students->insertMany($studentsData);

echo "Inserted Documents: "
    . $result->getInsertedCount();

Explanation

  • $studentsData is an array containing multiple student records.

  • Each inner array represents one document.

  • insertMany() inserts all supplied documents.

  • getInsertedCount() returns the number of inserted documents.

This method is useful when an application needs to insert multiple records together.

10. Retrieve All Documents Using find()

The find() method retrieves documents from a MongoDB collection.

Example:

$records = $students->find();

foreach ($records as $record) {

    echo "Name: " . htmlspecialchars($record['name']) . "<br>";

    echo "Age: " . htmlspecialchars((string) $record['age']) . "<br>";

    echo "Course: " . htmlspecialchars($record['course']) . "<br>";

    echo "City: " . htmlspecialchars($record['city']) . "<br>";

    echo "<hr>";
}

Explanation

  • find() retrieves matching documents.

  • The result is iterable.

  • foreach loops through each document.

  • htmlspecialchars() helps safely display values in HTML.

This is useful when displaying database records on a PHP webpage.

11. Retrieve One Document Using findOne()

If you want to retrieve only one matching document, use findOne().

Example:

$student = $students->findOne([
    'name' => 'Rahul'
]);

if ($student !== null) {

    echo "Student Name: "
        . htmlspecialchars($student['name']);

} else {

    echo "Student not found.";

}

Explanation

  • findOne() searches for the first document matching the filter.

  • name is the search field.

  • If a document is found, it is returned.

  • If no matching document exists, the result is null.

12. Retrieve Documents Using Query Conditions

MongoDB supports comparison operators that allow you to retrieve documents based on conditions.

Example: Find students whose age is greater than 21.

$records = $students->find([
    'age' => [
        '$gt' => 21
    ]
]);

foreach ($records as $record) {

    echo htmlspecialchars($record['name']) . "<br>";

}

Some useful MongoDB comparison operators are:

Operator Meaning
$gt Greater than
$gte Greater than or equal to
$lt Less than
$lte Less than or equal to
$eq Equal to
$ne Not equal to

Example: Find students whose age is greater than or equal to 22.

$records = $students->find([
    'age' => [
        '$gte' => 22
    ]
]);

13. Update a Document Using updateOne()

The updateOne() method updates the first document matching the given condition.

Example:

$result = $students->updateOne(
    ['name' => 'Rahul'],
    [
        '$set' => [
            'course' => 'Full Stack PHP'
        ]
    ]
);

echo "Matched Documents: " . $result->getMatchedCount();

echo "<br>";

echo "Modified Documents: " . $result->getModifiedCount();

Explanation

  • The first argument identifies the document.

  • $set changes the specified field.

  • getMatchedCount() returns the number of matched documents.

  • getModifiedCount() returns the number of documents actually modified.

If the matching document already has the same value, the modified count can be zero.

14. Delete a Document Using deleteOne()

The deleteOne() method deletes the first document matching the specified condition.

Example:

$result = $students->deleteOne([
    'name' => 'Rahul'
]);

echo "Deleted Documents: " . $result->getDeletedCount();

Explanation

  • deleteOne() searches for a matching document.

  • It deletes the first matching document.

  • getDeletedCount() returns the number of deleted documents.

Always use an appropriate filter when deleting data. A broad or incorrect filter can remove an unintended record.

15. Complete PHP MongoDB CRUD Program

Now let's combine the connection, insert, retrieve, update and delete operations into one practical PHP program.

Open index.php and use this complete code:

<?php

require_once __DIR__ . '/vendor/autoload.php';

use MongoDB\Client;

try {

    // MongoDB connection
    $uri = getenv('MONGODB_URI')
        ?: 'mongodb://127.0.0.1:27017/';

    $client = new Client($uri);

    // Test connection
    $client->selectDatabase('admin')->command(['ping' => 1]);

    echo "<h2>MongoDB Connected Successfully!</h2>";

    // Select database and collection
    $database = $client->selectDatabase('collegeDB');

    $students = $database->selectCollection('students');

    // Insert one document
    $student = [
        'name' => 'Rahul',
        'age' => 22,
        'course' => 'PHP',
        'city' => 'Raipur'
    ];

    $insertResult = $students->insertOne($student);

    $insertedId = $insertResult->getInsertedId();

    echo "<h3>Inserted ID: "
        . htmlspecialchars((string) $insertedId)
        . "</h3>";

    // Retrieve all documents
    echo "<h3>All Student Records</h3>";

    $records = $students->find();

    foreach ($records as $record) {

        echo "Name: "
            . htmlspecialchars($record['name'])
            . "<br>";

        echo "Age: "
            . htmlspecialchars((string) $record['age'])
            . "<br>";

        echo "Course: "
            . htmlspecialchars($record['course'])
            . "<br>";

        echo "City: "
            . htmlspecialchars($record['city'])
            . "<br><hr>";
    }

    // Retrieve one document
    echo "<h3>Find One Student</h3>";

    $result = $students->findOne([
        '_id' => $insertedId
    ]);

    if ($result !== null) {

        echo htmlspecialchars($result['name']);

    }

    // Update inserted document
    $updateResult = $students->updateOne(
        ['_id' => $insertedId],
        [
            '$set' => [
                'course' => 'Full Stack PHP'
            ]
        ]
    );

    echo "<h3>Modified Count: "
        . $updateResult->getModifiedCount()
        . "</h3>";

    // Delete inserted document
    $deleteResult = $students->deleteOne([
        '_id' => $insertedId
    ]);

    echo "<h3>Deleted Count: "
        . $deleteResult->getDeletedCount()
        . "</h3>";

} catch (Throwable $e) {

    echo "<h3>Error:</h3>";

    echo htmlspecialchars($e->getMessage());

}

How This Program Works

  1. Loads the Composer autoloader.

  2. Creates a MongoDB client.

  3. Checks the database connection using ping.

  4. Selects the collegeDB database.

  5. Selects the students collection.

  6. Inserts a student document.

  7. Retrieves all student records.

  8. Retrieves the inserted student by its _id.

  9. Updates the student's course.

  10. Deletes the same inserted document.

  11. Displays the operation results.

The program uses the inserted document's _id for update and delete operations. This ensures those operations target the exact document created during the current execution.

Note: This example is intended for learning. In a real application, separate database operations into reusable functions or classes, validate user input, and avoid displaying detailed database errors to public users.

16. Test the Data in MongoDB Compass

You can verify your PHP MongoDB operations using MongoDB Compass.

Follow these steps:

  1. Open MongoDB Compass.

  2. Connect to your local MongoDB server or Atlas cluster.

  3. Find the collegeDB database.

  4. Open the students collection.

  5. View the stored documents.

The complete CRUD program inserts a document and then deletes that same document. Therefore, the test document will not remain in the collection after the program finishes.

To keep the inserted record, temporarily comment out the deleteOne() section.

17. Common Errors and Their Solutions

Error 1: Class "MongoDB\Client" Not Found

Reason: The MongoDB PHP Library may not be installed, or Composer's autoloader is not included.

Solution:

composer require mongodb/mongodb

Also verify that your PHP file contains:

require_once __DIR__ . '/vendor/autoload.php';

Error 2: The MongoDB Extension Is Missing

Reason: The mongodb PHP extension is not installed or enabled.

Solution:

  • Install the compatible MongoDB PHP extension.

  • Enable it in the correct php.ini.

  • Restart Apache if you are using XAMPP.

  • Verify it using php -m.

Error 3: Server Selection Timeout

Reason: PHP cannot reach the MongoDB server.

Possible solutions:

  • Make sure MongoDB Server is running.

  • Verify the connection URI.

  • Check the MongoDB port.

  • Check network connectivity if using Atlas.

Error 4: Authentication Failed

Reason: The MongoDB Atlas username, password or database permissions may be incorrect.

Solution:

  • Verify your database username and password.

  • Check the user's database permissions.

  • Confirm that your IP address is allowed in Atlas Network Access.

  • URL-encode special characters in credentials included in the URI.

Error 5: Composer Command Not Found

Reason: Composer is not installed or is not available in the system PATH.

Solution:

Install Composer and reopen the terminal. Then verify:

composer --version

18. Best Practices for MongoDB with PHP

Follow these practices when developing PHP applications:

  1. Use the official MongoDB PHP Extension and PHP Library.

  2. Install dependencies through Composer.

  3. Keep database credentials outside publicly accessible source code.

  4. Use a reusable MongoDB client rather than creating a new client for every request.

  5. Validate data before inserting it into MongoDB.

  6. Use appropriate query filters for update and delete operations.

  7. Escape output before displaying database values in HTML.

  8. Handle database exceptions properly.

  9. Avoid exposing sensitive error details to public users.

  10. Use suitable indexes for frequently queried fields.

19. Practical Exercises

Try these exercises to improve your MongoDB and PHP skills.

Exercise 1: Connect PHP to your local MongoDB server.

Exercise 2: Create a database named schoolDB and a collection named teachers.

Exercise 3: Insert five teacher records using insertMany().

Exercise 4: Retrieve all teacher records using find().

Exercise 5: Search for a teacher by name using findOne().

Exercise 6: Find teachers whose experience is greater than five years.

Exercise 7: Update the subject of one teacher using updateOne().

Exercise 8: Delete one teacher record using deleteOne().

20. Frequently Asked Questions (FAQs)

Q1. Can we use MongoDB with PHP?

Yes. PHP applications can connect to MongoDB using the official MongoDB PHP Extension and MongoDB PHP Library.

Q2. Which library is used for MongoDB in PHP?

The official package is mongodb/mongodb, which is installed using Composer.

Q3. How do I install the MongoDB PHP Library?

Run this command inside your project folder:

composer require mongodb/mongodb

You must also install and enable the compatible MongoDB PHP Extension.

Q4. Which class is used to connect PHP with MongoDB?

The modern PHP Library uses:

use MongoDB\Client;

Q5. Which method inserts a document in MongoDB using PHP?

Use insertOne() for a single document and insertMany() for multiple documents.

Q6. How can I retrieve MongoDB records in PHP?

Use find() to retrieve multiple documents and findOne() to retrieve one matching document.

Q7. Can PHP connect to MongoDB Atlas?

Yes. PHP can connect to MongoDB Atlas using the Atlas connection URI and the official MongoDB PHP Library.

Q8. Is the old MongoClient class recommended?

No. The old MongoClient API belongs to outdated MongoDB PHP integrations. Modern PHP applications should use the official MongoDB\Client class.

Conclusion

Connecting PHP with MongoDB allows developers to build dynamic, data-driven web applications using a flexible NoSQL database.

In this tutorial, we learned how to install the MongoDB PHP Extension, install the official PHP Library using Composer, connect to MongoDB, create databases and collections, insert documents, retrieve records, update data and delete documents.

These concepts are useful for developing student management systems, inventory applications, blog websites, content management systems and other PHP-based projects.

Practice the examples step by step to strengthen your understanding of MongoDB and PHP integration.

←
Post 27 of 35
→