Current Location: Home> Latest Articles> Complete Guide: How to Set Up and Use MongoDB with PHP (Install, Query, Update, Delete)

Complete Guide: How to Set Up and Use MongoDB with PHP (Install, Query, Update, Delete)

M66 2025-10-20

How to Set Up and Use MongoDB with PHP

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.

Install MongoDB PHP Extension

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

Connect to MongoDB Server

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.

Select Database and Collection

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.

Insert Document

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.

Query Documents

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.”

Update Documents

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.”

Delete Documents

To delete data, execute the following code:

$filter = ["name" => "John Doe"];
$collection->deleteOne($filter);

This deletes the first document that matches the specified condition.

Conclusion

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.