MongoDB CRUD with PHP: Create, Read, Update, and Delete

PHP gives us the ability to work with MongoDB, highlighting the importance of CRUD (Create, Read, Update, Delete) operations for database management.

Here are some requirements to start using MongoDB with PHP:

  1. Installing MongoDB
  2. Installing PHP MongoDB Driver
  3. Setting Up a Development Environment ( XAMPP, Docker, or direct Apache/Nginx configurations )

Let us move on to the following section to understand what CRUD means and how to use it to access a MongoDB database.

What does Mean CRUD in MongoDB?

In MongoDB, the term CRUD refers to the four primary operations used to manage data: Create, Read, Update, and Delete:

  • The Create operation allows you to insert new documents into a collection. For example, you can add user data or any other type of information to the database.
  • Read operation which used to query and retrieve data from a database. You can filter, sort, and project the data as needed.
  • Update operation which helps us to modify existing documents in a collection. You can update specific fields or replace entire documents.
  • Delete operation to remove documents from a collection. You can specify criteria to delete specific documents or remove all documents in a collection.

Let’s see an example for each one.

Examples of CRUD in MongoDB and PHP

Create

The “Create” operation is all about adding new data to your database. Here is how you can add a document:

$collection = $database->selectCollection('users');
$result = $collection->insertOne(['name' => 'John Doe', 'email' => 'john@example.com']);
echo "Inserted document with ID: " . $result->getInsertedId();

Before insert a new document to database, you need to select the users collection. Adding a document with the name and email fields, and the database automatically generates a unique _id for it. The getInsertedId() method then gives you that ID.

Read

The ‘Read’ operation is used to retrieve data from the database. Let’s see how to do it:

$collection = $database->selectCollection('users');
$result = $collection->findOne(['name' => 'John Doe']);
echo "Found User: " . $result['email'];

Here, you are asking the database to find the first document where the name is “John Doe.” The findOne method brings it back as an associative array, and you can access specific fields, like email.

Update

Updating means modifying an existing entry. Say you want to change John’s email. Here is how you do it:

$collection = $database->selectCollection('users');
$updateResult = $collection->updateOne(
    ['name' => 'John Doe'],
    ['$set' => ['email' => 'john.doe@example.com']]
);
echo "Updated " . $updateResult->getModifiedCount() . " document(s)";

This code searches for a document with the name “John Doe” and updates the email field to the new value. The getModifiedCount() method tells you how many documents were successfully updated.

Delete

The ‘Delete’ operation is responsible for removing data from the database. If John no longer needs to be in your collection, you can remove him like this:

$collection = $database->selectCollection('users');
$deleteResult = $collection->deleteOne(['name' => 'John Doe']);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s)";

Here, you are specifying the criteria (name: 'John Doe') for deletion, and the getDeletedCount() method confirms how many documents were removed.

Let’s summarize it.

Wrapping Up

That is the essence of CRUD operations in MongoDB: Create, Read, Update, and Delete. These four operations form the basis of how you interact with your database.

Here is a quick recap:

  • Create: Add new documents to your collection using methods like insertOne() or insertMany().
  • Read: Retrieve documents from the database with methods like findOne() or find() for more complex queries.
  • Update: Modify existing documents using methods like updateOne() or updateMany() with operators like $set or $inc.
  • Delete: Remove documents from your collection using methods like deleteOne() or deleteMany().

Each operation is a critical piece of database management, giving you full control over your data. 

Similar Reads

PHP DOMDocument: XML DOM Parser Guide

In PHP, if you're working with XML files, you’ll probably work with DOMDocument. It is a powerful class, enabling you…

PHP Switch | How the Switch Statement Works in PHP

The PHP switch statement is multiple conditions to only execute one block if its condition generating a true boolean value.…

PHP require_once and require

Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…

Inheritance in PHP: Share Code from Class to Class & Examples

PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in…

PHP Array: Accessing and Managing Elements

PHP arrays are lists or maps that contain multiple values grouped by array keys. They may include integers, strings, booleans,…

PHP array_any: How it Works with Arrays with Examples

PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…

PHP Spread Operator: Understand How (…) Syntax Works

Before the spread operator, PHP developers had to pass array items to a function using extra steps. They often had…

PHP OR Operator: Using || and or in Conditional Statements

The PHP OR operator has two renditions: either || or or. Both of these are useful logical operators when you want to introduce…

PHP file_exists: Check File and Directory Existence

Whether you are just trying to keep your app from crashing or making sure your users’ uploads don’t accidentally overwrite…

PHP array_intersect_assoc: How it Works with Examples

PHP array_intersect_assoc compares values and keys in arrays. It returns matches with the same key and value from all arrays…

Previous Article

How to Connect PHP to MongoDB

Next Article

Learn How to Insert Documents in MongoDB Using PHP

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.