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

    

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
>
>:youtube]{vid=tW87xDCPspk}

Let's start with an overview of what we'll cover in this article.

1. [Connecting to a MongoDB Database Instance
1. Creating or Inserting a Single MongoDB Document with PHP
1. Creating or Inserting Multiple MongoDB Documents with PHP
1. Reading Documents with PHP
1. Updating Documents with PHP
1. Deleting Documents with PHP

## Connecting to a MongoDB Database Instance

To connect to a MongoDB Atlas cluster, use the Atlas connection string for your cluster:

``` php
:@/test?w=majority'
);
$db = $client->test;
```

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

``` bash
MDB_USER="yourusername"
MDB_PASS="yourpassword"
ATLAS_CLUSTER_SRV="mycluster.zbcul.mongodb.net"
```

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.

``` bash
$ composer require vlucas/phpdotenv
```

Once installed, you can incorporate this library into your code to pull in the values from your `.env` file.

``` php
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
```

Next, you will be able to reference the values from the `.env` file using the `$_ENV]` array like this:

``` php
echo $_ENV['MDB_USER'];
```

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:

``` php
load();

$client = new MongoDB\Client(
   'mongodb+srv://'.$_ENV'MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);

$collection = $client->test->users;

$insertOneResult = $collection->insertOne([
   'username' => 'admin',
   'email' => 'admin@example.com',
   'name' => 'Admin User',
]);

printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());

var_dump($insertOneResult->getInsertedId());
```

You should see something similar to:

``` bash
Inserted 1 document(s)
object(MongoDB\BSON\ObjectId)#11 (1) {
   ["oid"]=>
   string(24) "579a25921f417dd1e5518141"
}
```

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:

``` php
load();

$client = new MongoDB\Client(
   'mongodb+srv://'.$_ENV'MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
);

$collection = $client->test->users;

$insertManyResult = $collection->insertMany([
   [
      'username' => 'admin',
      'email' => 'admin@example.com',
      'name' => 'Admin User',
   ],
   [
      'username' => 'test',
      'email' => 'test@example.com',
      'name' => 'Test User',
   ],
]);

printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());

var_dump($insertManyResult->getInsertedIds());
```

You should see something similar to the following:

``` bash
Inserted 2 document(s)
array(2) {
[0]=>
   object(MongoDB\BSON\ObjectId)#18 (1) {
      ["oid"]=>
      string(24) "6037b861301e1d502750e712"
   }
   [1]=>
   object(MongoDB\BSON\ObjectId)#21 (1) {
      ["oid"]=>
      string(24) "6037b861301e1d502750e713"
   }
}
```

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

``` php
function find($filter = [], array $options = []): MongoDB\Driver\Cursor
```

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.

``` php
load();

$client = new MongoDB\Client(
   'mongodb+srv://'.$_ENV'MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/sample_restaurants'
);

$collection = $client->sample_restaurants->restaurants;

$cursor = $collection->find(
   [
      'cuisine' => 'Italian',
      'borough' => 'Manhattan',
   ],
   [
      'limit' => 5,
      'projection' => [
            'name' => 1,
            'borough' => 1,
            'cuisine' => 1,
      ],
   ]
);

foreach ($cursor as $restaurant) {
   var_dump($restaurant);
};
```

You should see something similar to the following output:

``` bash
object(MongoDB\Model\BSONDocument)#20 (1) {
["storage":"ArrayObject":private]=>
   array(4) {
      ["_id"]=>
      object(MongoDB\BSON\ObjectId)#26 (1) {
         ["oid"]=>
         string(24) "5eb3d668b31de5d588f42965"
      }
      ["borough"]=>
      string(9) "Manhattan"
      ["cuisine"]=>
      string(7) "Italian"
      ["name"]=>
      string(23) "Isle Of Capri Resturant"
   }
}
object(MongoDB\Model\BSONDocument)#19 (1) {
["storage":"ArrayObject":private]=>
   array(4) {
      ["_id"]=>
      object(MongoDB\BSON\ObjectId)#24 (1) {
         ["oid"]=>
         string(24) "5eb3d668b31de5d588f42974"
      }
      ["borough"]=>
      string(9) "Manhattan"
      ["cuisine"]=>
      string(7) "Italian"
      ["name"]=>
      string(18) "Marchis Restaurant"
   }
}
object(MongoDB\Model\BSONDocument)#26 (1) {
["storage":"ArrayObject":private]=>
   array(4) {
      ["_id"]=>
      object(MongoDB\BSON\ObjectId)#20 (1) {
         ["oid"]=>
         string(24) "5eb3d668b31de5d588f42988"
      }
      ["borough"]=>
      string(9) "Manhattan"
      ["cuisine"]=>
      string(7) "Italian"
      ["name"]=>
      string(19) "Forlinis Restaurant"
   }
}
object(MongoDB\Model\BSONDocument)#24 (1) {
["storage":"ArrayObject":private]=>
   array(4) {
      ["_id"]=>
      object(MongoDB\BSON\ObjectId)#19 (1) {
         ["oid"]=>
         string(24) "5eb3d668b31de5d588f4298c"
      }
      ["borough"]=>
      string(9) "Manhattan"
      ["cuisine"]=>
      string(7) "Italian"
      ["name"]=>
      string(22) "Angelo Of Mulberry St."
   }
}
object(MongoDB\Model\BSONDocument)#20 (1) {
["storage":"ArrayObject":private]=>
   array(4) {
      ["_id"]=>
      object(MongoDB\BSON\ObjectId)#26 (1) {
         ["oid"]=>
         string(24) "5eb3d668b31de5d588f42995"
      }
      ["borough"]=>
      string(9) "Manhattan"
      ["cuisine"]=>
      string(7) "Italian"
      ["name"]=>
      string(8) "Arturo'S"
   }
}
```

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

``` php
load();

$client = new MongoDB\Client(
   'mongodb+srv://'.$_ENV'MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/sample_restaurants'
);

$collection = $client->sample_restaurants->restaurants;

$updateResult = $collection->updateOne(
   [ 'restaurant_id' => '40356151' ],
   [ '$set' => [ 'name' => 'Brunos on Astoria' ]]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
```

You should see something similar to the following output:

``` bash
Matched 1 document(s)
Modified 1 document(s) 
```

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:

``` php
load();

$client = new MongoDB\Client(
   'mongodb+srv://'.$_ENV'MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/sample_restaurants'
);

$collection = $client->sample_restaurants->restaurants;

$updateResult = $collection->updateMany(
   [ 'borough' => 'Queens' ],
   [ '$set' => [ 'active' => 'True' ]]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
```

You should see something similar to the following:

``` bash
Matched 5656 document(s)
Modified 5656 document(s)
```

>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:

``` php
$collection = (new MongoDB\Client)->selectCollection('test', 'users', [
   'writeConcern' => new MongoDB\Driver\WriteConcern(1, 0, true),
]);

var_dump($collection->getWriteConcern());
```

See  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:

``` php
load();

$client = new MongoDB\Client(
   'mongodb+srv://'.$_ENV'MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/sample_restaurants'
);

$collection = $client->sample_restaurants->restaurants;

$deleteResult = $collection->deleteOne(['cuisine' => 'Hamburgers']); 

printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
```

You should see something similar to the following output:

``` bash
Deleted 1 document(s)
```

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

``` php
load();

   $client = new MongoDB\Client(
      'mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/sample_restaurants'
   );

   $collection = $client->sample_restaurants->restaurants;
   $deleteResult = $collection->deleteMany(['cuisine' => 'Hamburgers']);

   printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());      
```

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:  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:

-   [MongoDBCollection::insertOne
-   MongoDBCollection::insertMany

Reading or finding documents is accomplished using:

-   MongoDBCollection::find

Updating documents is accomplished through the use of:

-   MongoDBCollection::updateOne
-   MongoDBCollection::updateMany

Deleting or removing documents is accomplished using:

-   MongoDBCollection::deleteOne
-   MongoDBCollection::deleteMany

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

-   MongoDB PHP Quickstart Source Code Repository
-   MongoDB PHP Driver CRUD Documentation
-   MongoDB PHP Driver Documentation provides thorough documentation describing how to use PHP with our MongoDB cluster.
-   MongoDB Query Document documentation details the full power available for querying MongoDB collections.