How to use MongoDB in PHP

Updated: January 12, 2024 By: Guest Contributor Post a comment

Introduction to MongoDB

MongoDB is a popular NoSQL database that is known for its scalability and flexibility. It allows you to store documents in a JSON-like format, making it incredibly attractive for applications that require a dynamic schema. In this tutorial, we will learn how to use MongoDB with PHP, a widely-used server-side scripting language that powers a significant portion of the web.

Setting Up the Environment

Before we dive into the code, it’s essential to set up the environment. This means you need to have MongoDB and PHP installed on your system.

Installing MongoDB

Install MongoDB by following the official instructions provided here. Make sure you install the community edition of MongoDB, which is free and open-source.

Installing PHP

You can download and install PHP from php.net. Make sure you install PHP with either the thread-safe or non-thread-safe version, depending on your operating system and use case.

Installing the MongoDB PHP Driver

You’ll need to install the MongoDB PHP driver to interact with your MongoDB instance using PHP. You can do this with PECL, which is a repository for PHP extensions. Run the following command:

pecl install mongodb

After installing the driver, you need to add it to your php.ini file:

extension=mongodb.so

Storing Data in MongoDB Using PHP

Lets store some data! First, create a new instance of the MongoDB client.

require_once 'vendor/autoload.php';

use MongoDB\Client;

$client = new Client('mongodb://127.0.0.1/');

Next, select your database and collection:

$db = $client->myDatabase;
$collection = $db->users;

Add a document to the collection:

$insertOneResult = $collection->insertOne([
    'name' => 'Jane Doe',
    'email' => '[email protected]',
    'age' => 27
]);

echo "Inserted with Object ID '{
$insertOneResult->getInsertedId()
}';"

Querying Data From MongoDB

To retrieve data from MongoDB, we can use various query methods provided by MongoDB PHP library. The following example shows how you can find a single document by a field value:

$document = $collection->findOne(['name' => 'Jane Doe']);

var_dump($document);

To fetch all documents with certain criteria, use find():

foreach ($collection->find(['age' => ['$gt' => 20]]) as $doc) {
    var_dump($doc);
}

Updating Data in MongoDB

Updating is a common operation, here’s how you can perform it with the MongoDB PHP library:

$updateResult = $collection->updateOne(
    ['name' => 'Jane Doe'],
    ['$set' => ['age' => 28]]
);

echo "Matched {
$updateResult->getMatchedCount()
} document(s)\nUpdated {
$updateResult->getModifiedCount()
} document(s)";

Deleting Data From MongoDB

Delete operations are also straightforward. Here’s an example to remove a document:

$deleteResult = $collection->deleteOne(['name' => 'Jane Doe']);

echo "Deleted {
$deleteResult->getDeletedCount()
} document(s)";

Advanced Queries and MongoDB Aggregation

MongoDB offers advanced query capabilities and aggregation tools. PHP’s MongoDB library provides methods to utilize these features. Here’s a quick overview:

$cursor = $collection->aggregate([
    ['$match' => ['age' => ['$gte' => 30]]],
    ['$group' => ['_id' => '$age', 'count' => ['$sum' => 1]]]
]);

foreach ($cursor as $document) {
    echo "Age {
$document->_id
}: Count {
$document->count
}";
}

Handling Connections and Errors

Always handle possible exceptions and errors when dealing with database operations:

try {
    // perform operations here
} catch (\MongoDB\\Exception\\Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Conclusion

Using MongoDB with PHP can seem daunting at first, but with the right tools and techniques, it becomes straightforward. This guide has given you the basic steps to get started. Remember to consult the official MongoDB PHP library documentation for more advanced usage and features. Happy coding!