Here's an example of a PHP function for establishing a MongoDB connection:


// Source:

function connectToMongoDB($host, $port, $database, $username, $password) {

    try {

        $client = new MongoDB\Client("mongodb://{$username}:{$password}@{$host}:{$port}/{$database}");

        return $client->selectDatabase($database);

    } catch (MongoDB\Driver\Exception\ConnectionException $e) {

        // Handle connection error

        echo "Failed to connect to MongoDB: " . $e->getMessage();




In this function, you need to pass the MongoDB server details such as host, port, database name, username, and password. The function uses the MongoDB PHP library to create a new MongoDB\Client object and establish a connection to the MongoDB server.

To use this function, you can call it and store the returned MongoDB database object for further operations:

$mongoDB = connectToMongoDB("localhost", 27017, "mydatabase", "username", "password");

Make sure to replace "localhost", 27017, "mydatabase", "username", and "password" with your actual MongoDB server details.

Note: Before using this function, you'll need to install the MongoDB PHP library if it's not already installed. You can install it using Composer or by following the installation instructions provided by the library.