How Do I Connect MongoDB Using PHP Scripts in Google Cloud Functions?

Hi everyone,

I’m currently facing a challenge while integrating MongoDB with a PHP script in Google Cloud Functions. My goal is to run a Google Cloud function that connects to MongoDB using PHP. Although I’ve found numerous resources, they predominantly focus on Node.js implementations, leaving me a bit in the dark with PHP.

Here’s where I’m at:

  • I have been attempting to execute this function on Google Cloud, but I’m encountering a critical error: PHP message: PHP Fatal error: Uncaught Error: Class "MongoDB\Client" not found in /workspace/index.php:13.
    PHP message: PHP Warning: The use statement with non-compound name ‘Exception’ has no effect in /workspace/index.php on line 3
  • This leads me to believe that the main issue lies in installing the MongoDB PHP driver within the Google Cloud function environment.

This is my current code


use Exception;
use MongoDB\Client;
use Google\CloudFunctions\CloudEvent;

function main(CloudEvent $cloudevent){

  // Replace the placeholder with your Atlas connection string
  $uri =  "";

  // Create a new client and connect to the server
  $client = new MongoDB\Client($uri);
  echo $client;

  try {
      // Send a ping to confirm a successful connection
      $client->selectDatabase('admin')->command(['ping' => 1]);
      echo "Pinged your deployment. You successfully connected to MongoDB!\n";
  } catch (Exception $e) {

I’m reaching out for advice on how to properly install and configure the MongoDB PHP driver in Google Cloud Functions. Has anyone here successfully tackled this? Any insights or step-by-step guidance would be incredibly helpful.

Additionally, if you’ve encountered similar issues or have relevant troubleshooting tips, I’d greatly appreciate your input.

Thank you in advance for your help!