Using MongoDB in PHP is straightforward. With just a few lines of code, you can install the extension and perform CRUD operations. This guide walks you through the complete process from installation to practical use.
First, install the MongoDB PHP extension using the following command:
pecl install mongodb
After installation, enable the extension by adding the following line to your php.ini file:
extension=mongodb.so
Once the extension is installed, you can connect to the MongoDB server using the following PHP code:
<?php
$client = new MongoDB\Client("mongodb://localhost:27017");
Here, localhost:27017 is the address and port of your MongoDB server. You can adjust it according to your setup.
After connecting, select the desired database and collection with this code:
$db = $client->my_database;
$collection = $db->my_collection;
This example selects a database named my_database and a collection named my_collection.
To insert data into MongoDB, use the following example:
$document = ["name" => "John Doe"];
$collection->insertOne($document);
This command inserts a document with a name field into the collection.
To read data from MongoDB, use the find() method:
$filter = ["name" => "John Doe"];
$cursor = $collection->find($filter);
foreach ($cursor as $document) {
// Process each document
}
This retrieves all documents where the name is “John Doe.”
To modify data, use the updateOne() method:
$filter = ["name" => "John Doe"];
$update = ["$set" => ["age" => 30]];
$collection->updateOne($filter, $update);
This updates the age field to 30 for the document with the name “John Doe.”
To delete data, execute the following code:
$filter = ["name" => "John Doe"];
$collection->deleteOne($filter);
This deletes the first document that matches the specified condition.
By following these steps, you can set up and operate MongoDB with PHP efficiently — from installing the extension to performing CRUD operations. Once you master these basics, integrating MongoDB into your PHP projects becomes much easier and more powerful.