Connect to MongoDB
After retrieving the connection string for your MongoDB Atlas deployment, you can connect to the deployment from your PHP application and query the Atlas sample datasets.
Edit your PHP application file
Copy and paste the following code into the quickstart.php
file, which queries
the movies
collection in the sample_mflix
database:
require __DIR__ . '/../vendor/autoload.php'; use MongoDB\Client; $client = new Client('<connection string>'); $collection = $client->sample_mflix->movies; $filter = ['title' => 'The Shawshank Redemption']; $result = $collection->findOne($filter); if ($result) { echo json_encode($result, JSON_PRETTY_PRINT); } else { echo "Document not found"; }
Assign the connection string
Replace the <connection string>
placeholder with the
connection string that you copied from the Create a Connection String
step of this guide.
Run your PHP application
In your project directory, run the following shell command to start the application:
php quickstart.php
The command line output contains details about the retrieved movie document:
{ "_id": { "$oid": "..." }, ... "rated": "R", "metacritic": 80, "title": "The Shawshank Redemption", ... }
If you encounter an error or see no output, ensure that you specified the
proper connection string in the quickstart.php
file and that you loaded the
sample data.
After you complete these steps, you have a PHP application that connects to your MongoDB deployment, runs a query on the sample data, and returns a matching document.
Note
If you run into issues on this step, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of this page.