EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
PHP
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
PHPchevron-right

Creating, Reading, Updating, and Deleting MongoDB Documents with PHP

Michael Lynn8 min read • Published Feb 05, 2022 • Updated Aug 24, 2023
MongoDBPHP
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
PHP badge
Welcome to Part 2 of this quick start guide for MongoDB and PHP. In the previous article, I walked through the process of installing, configuring, and setting up PHP, Apache, and the MongoDB Driver and Extension so that you can effectively begin building an application leveraging the PHP, MongoDB stack.
I highly recommend visiting the first article in this series to get set up properly if you have not previously installed PHP and Apache.
I've created each section with code samples. And I'm sure I'm much like you in that I love it when a tutorial includes examples that are standalone... They can be copy/pasted and tested out quickly. Therefore, I tried to make sure that each example is created in a ready-to-run fashion.
These samples are available in this repository, and each code sample is a standalone program that you can run by itself. In order to run the samples, you will need to have installed PHP, version 8, and you will need to be able to install additional PHP libraries using Compose. These steps are all covered in the first article in this series.
Additionally, while I cover it in this article, it bears mentioning upfront that you will need to create and use a .env file with your credentials and the server name from your MongoDB Atlas cluster.
This guide is organized into a few sections over a few articles. This first article addresses the installation and configuration of your development environment. PHP is an integrated web development language. There are several components you typically use in conjunction with the PHP programming language.
Video Introduction and Overview
Let's start with an overview of what we'll cover in this article.

Connecting to a MongoDB Database Instance

To connect to a MongoDB Atlas cluster, use the Atlas connection string for your cluster:
Just a note about language. Throughout this article, we use the term create and insert interchangeably. These two terms are synonymous. Historically, the act of adding data to a database was referred to as CREATING. Hence, the acronym CRUD stands for Create, Read, Update, and Delete. Just know that when we use create or insert, we mean the same thing.

Protecting Sensitive Authentication Information with DotEnv (.env)

When we connect to MongoDB, we need to specify our credentials as part of the connection string. You can hard-code these values into your programs, but when you commit your code to a source code repository, you're exposing your credentials to whomever you give access to that repository. If you're working on open source, that means the world has access to your credentials. This is not a good idea. Therefore, in order to protect your credentials, we store them in a file that does not get checked into your source code repository. Common practice dictates that we store this information only in the environment. A common method of providing these values to your program's running environment is to put credentials and other sensitive data into a .env file.
The following is an example environment file that I use for the examples in this tutorial.
To create your own environment file, create a file called .env in the root of your program directory. You can simply copy the example environment file I've provided and rename it to .env. Be sure to replace the values in the file yourusername, yourpassword, and mycluster.zbcul.mongodb.net with your own.
Once the environment file is in place, you can use Composer to install the DotEnv library, which will enable us to read these variables into our program's environment. See the first article in this series for additional setup instructions.
Once installed, you can incorporate this library into your code to pull in the values from your .env file.
Next, you will be able to reference the values from the .env file using the $_ENV[] array like this:
See the code examples below to see this in action.

Creating or Inserting a Single MongoDB Document with PHP

The MongoDBCollection::insertOne() method inserts a single document into MongoDB and returns an instance of MongoDBInsertOneResult, which you can use to access the ID of the inserted document.
The following code sample inserts a document into the users collection in the test database:
You should see something similar to:
The output includes the ID of the inserted document.

Creating or Inserting Multiple MongoDB Documents with PHP

The MongoDBCollection::insertMany() method allows you to insert multiple documents in one write operation and returns an instance of MongoDBInsertManyResult, which you can use to access the IDs of the inserted documents.
The following sample code inserts two documents into the users collection in the test database:
You should see something similar to the following:

Reading Documents with PHP

Reading documents from a MongoDB database can be accomplished in several ways, but the most simple way is to use the $collection->find() command.
Read more about the find command in PHP here:.
The following sample code specifies search criteria for the documents we'd like to find in the restaurants collection of the sample_restaurants database. To use this example, please see the Available Sample Datasets for Atlas Clusters.
You should see something similar to the following output:

Updating Documents with PHP

Updating documents involves using what we learned in the previous section for finding and passing the parameters needed to specify the changes we'd like to be reflected in the documents that match the specific criterion.
There are two specific commands in the PHP Driver vocabulary that will enable us to update documents.
  • MongoDB\Collection::updateOne - Update, at most, one document that matches the filter criteria. If multiple documents match the filter criteria, only the first matching document will be updated.
  • MongoDB\Collection::updateMany - Update all documents that match the filter criteria.
These two work very similarly, with the obvious exception around the number of documents impacted.
Let's start with MongoDB\Collection::updateOne. The following code sample finds a single document based on a set of criteria we pass in a document and $set's values in that single document.
You should see something similar to the following output:
Now, let's explore updating multiple documents in a single command execution.
The following code sample updates all of the documents with the borough of "Queens" by setting the active field to true:
You should see something similar to the following:
When updating data in your MongoDB database, it's important to consider write concern. Write concern describes the level of acknowledgment requested from MongoDB for write operations to a standalone mongod, replica sets, or sharded clusters.
To understand the current value of write concern, try the following example code:
See https://docs.mongodb.com/manual/reference/write-concern/ for more information on write concern.

Deleting Documents with PHP

Just as with updating and finding documents, you have the ability to delete a single document or multiple documents from your database.
  • MongoDB\Collection::deleteOne - Deletes, at most, one document that matches the filter criteria. If multiple documents match the filter criteria, only the first matching document will be deleted.
  • MongoDB\Collection::deleteMany - Deletes all documents that match the filter criteria.
Let's start with deleting a single document.
The following code sample deletes one document in the users collection that has "ny" as the value for the state field:
You should see something similar to the following output:
You will notice, if you examine the sample_restaurants database, that there are many documents matching the criteria { "cuisine": "Hamburgers" }. However, only one document was deleted.
Deleting multiple documents is possible using MongoDB\Collection::deleteMany. The following code sample shows how to use deleteMany.
You should see something similar to the following output:
Deleted 432 document(s)
If you run this multiple times, your output will obviously differ. This is because you may have removed or deleted documents from prior executions. If, for some reason, you want to restore your sample data, visit: https://docs.atlas.mongodb.com/sample-data/available-sample-datasets/ for instructions on how to do this.

Summary

The basics of any language are typically illuminated through the process of creating, reading, updating, and deleting data. In this article, we walked through the basics of CRUD with PHP and MongoDB. In the next article in the series, will put these principles into practice with a real-world application.
Creating or inserting documents is accomplished through the use of:
Reading or finding documents is accomplished using:
Updating documents is accomplished through the use of:
Deleting or removing documents is accomplished using:
Please be sure to visit, star, fork, and clone the companion repository for this article.
Questions? Comments? We'd love to connect with you. Join the conversation on the MongoDB Community Forums.

References


Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Article

Handling MongoDB PHP Errors


Feb 03, 2023 | 7 min read
Quickstart

Getting Set Up to Run PHP with MongoDB


Jan 31, 2024 | 12 min read
Podcast

Exploring the PHP Driver with Jeremy Mikola - Podcast Episode


May 16, 2022 | 29 min
Industry Event
locationPARIS, FRANCE | IN-PERSON

SymfonyLive Paris 2024


Mar 28, 2024 - Mar 29, 2024
Table of Contents