Basic Usage of MongoDB in a PHP Application

In this article, we’ll explore the fundamental steps to use MongoDB in a PHP application.

Posted on

MongoDB, a NoSQL database, is often used in web development alongside PHP to store and manage unstructured or semi-structured data efficiently. In this article, we’ll explore the fundamental steps to use MongoDB in a PHP application. We’ll cover database connection, data manipulation, and error handling to help you get started.

Prerequisites

Before we begin, ensure you have the following prerequisites:

  1. MongoDB: MongoDB should be installed and running on your server or local development environment. You can download MongoDB from the official MongoDB website.

  2. PHP: Make sure you have PHP installed. You can download PHP from the official PHP website.

  3. MongoDB PHP Driver: Install the MongoDB PHP driver, which provides functions for interacting with MongoDB. You can install it using pecl, the PHP Extension Community Library:

    pecl install mongodb
    

    After installation, add extension=mongodb.so to your PHP configuration file (e.g., php.ini).

Step 1: Connecting to MongoDB

To connect to a MongoDB database from a PHP application, you’ll need to use the MongoDB PHP driver. Create a connection to the MongoDB server:

<?php
$mongoClient = new MongoDB\Driver\Manager("mongodb://localhost:27017");
?>

Replace "mongodb://localhost:27017" with the appropriate connection string if MongoDB is running on a different host or port.

Step 2: Inserting Data

MongoDB stores data in collections, which are similar to tables in relational databases. Let’s start by inserting data into a collection.

<?php
$bulk = new MongoDB\Driver\BulkWrite;

// Define the document to insert
$document = [
    '_id' => new MongoDB\BSON\ObjectID,
    'name' => 'John Doe',
    'email' => '[email protected]'
];

// Insert the document into the "users" collection
$bulk->insert($document);

// Execute the bulk write operation
$result = $mongoClient->executeBulkWrite('your_database_name.users', $bulk);

if ($result) {
    echo "Data inserted successfully";
} else {
    echo "Error inserting data";
}
?>

Replace 'your_database_name' with the name of your MongoDB database.

Step 3: Querying Data

You can retrieve data from MongoDB collections using queries. Here’s an example of retrieving all documents from the “users” collection:

<?php
$filter = [];
$options = [];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $mongoClient->executeQuery('your_database_name.users', $query);

foreach ($cursor as $document) {
    echo "Name: " . $document->name . ", Email: " . $document->email . "<br>";
}
?>

Step 4: Updating and Deleting Data

Updating and deleting data in MongoDB is straightforward. Here’s an example of updating a user’s email address:

<?php
$filter = ['name' => 'John Doe'];
$update = ['$set' => ['email' => '[email protected]']];

$updateOptions = [
    'multi' => false,  // Update only one document
    'upsert' => false  // Do not insert if the document does not exist
];

$updateQuery = new MongoDB\Driver\BulkWrite;
$updateQuery->update($filter, $update, $updateOptions);

$result = $mongoClient->executeBulkWrite('your_database_name.users', $updateQuery);

if ($result) {
    echo "Data updated successfully";
} else {
    echo "Error updating data";
}
?>

And here’s an example of deleting a user:

<?php
$filter = ['name' => 'John Doe'];
$deleteOptions = ['limit' => 1];  // Delete only one document

$deleteQuery = new MongoDB\Driver\BulkWrite;
$deleteQuery->delete($filter, $deleteOptions);

$result = $mongoClient->executeBulkWrite('your_database_name.users', $deleteQuery);

if ($result) {
    echo "User deleted successfully";
} else {
    echo "Error deleting user";
}
?>

Step 5: Error Handling and Closing the Connection

Always handle errors gracefully and close the MongoDB connection when done.

<?php
// Closing the MongoDB connection
unset($mongoClient);
?>

Conclusion

In this article, we’ve covered the basic usage of MongoDB in a PHP application. You’ve learned how to connect to a MongoDB database, insert data, query data, update records, and delete records. MongoDB is a versatile NoSQL database, and these fundamental skills will serve as a solid foundation for building database-driven PHP web applications. As you continue your journey in web development, you’ll explore more complex database operations and best practices for secure and efficient data management.