Docs Menu
Docs Home
/ / /
PHP Library Manual
/

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.

1

Copy and paste the following code into the quickstart.php file, which queries the movies collection in the sample_mflix database:

<?php
require __DIR__ . '/../vendor/autoload.php';
use MongoDB\Client;
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException(
'Set the MONGODB_URI environment variable to your Atlas URI'
);
$client = new MongoDB\Client($uri);
$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';
}
2

Assign the MONGODB_URI environment variable to the connection string that you copied from the Create a Connection String step of this guide. You can assign this variable by running a shell command or creating a .env file in your application, as show in the following tabs:

export MONGODB_URI=<connection string>
MONGODB_URI=<connection string>
3

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 assigned the proper connection string to the MONGODB_URI environment variable 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.

Back

Create a Connection String