tencent cloud

TencentDB for MongoDB

PHP SDK

다운로드
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-06-11 11:36:11

Scenarios

PHP is widely used in web application development thanks to its ease of deployment and rich ecosystem. The MongoDB PHP Library provides a concise, object-oriented API built on top of the underlying mongodb extension. This document walks you through a complete example of using PHP to connect to TencentDB for MongoDB, covering both the underlying extension and the high-level library.

Prerequisites

You have created a TencentDB for MongoDB instance, and the instance status is Running.
You have prepared a CVM instance that resides in the same VPC as the MongoDB instance, and you have installed PHP version 7.4 or later.

Installing a Driver

To connect PHP to MongoDB, you need to install two components:
Component
Type
Description
mongodb extension
PHP C extension (underlying)
Provides underlying BSON and network communication capabilities.
mongodb/mongodb library
Composer package (upper layer, recommended)
An object-oriented API encapsulated based on the underlying extension
Install the underlying extension:
pecl install mongodb
After the installation is complete, add the following to php.ini:
extension=mongodb.so
Install the high-level library:
composer require mongodb/mongodb

Method 1: Using the MongoDB PHP Library (Recommended)

The MongoDB PHP Library provides a concise, object-oriented API and is the recommended approach.
<?php
require_once __DIR__ . '/vendor/autoload.php';

use MongoDB\\Client;
use MongoDB\\Exception\\RuntimeException;

// Connection URI (Replace with your actual connection information)
$uri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin';

try {
// Create a client connection.
$client = new Client($uri, [
'retryWrites' => true,
'w' => 'majority',
], [
'typeMap' => [
'root' => 'array',
'document' => 'array',
'array' => 'array',
],
]);

// Select a database and a collection.
$collection = $client->mydb->users;

// ========== Insert a Document ==========
$result = $collection->insertOne([
'username' => 'jack',
'age' => 31,
'email' => 'jack@example.com',
'createdAt' => new MongoDB\\BSON\\UTCDateTime(),
]);
printf("Inserted document ID: %s\\n", $result->getInsertedId());

// Batch Insert
$result = $collection->insertMany([
['username' => 'alice', 'age' => 28, 'email' => 'alice@example.com'],
['username' => 'bob', 'age' => 35, 'email' => 'bob@example.com'],
]);
printf("Batch inserted %d documents\\n", $result->getInsertedCount());

// ========== Query Documents ==========
$user = $collection->findOne(['username' => 'jack']);
printf("Query a single document: %s\\n", json_encode($user, JSON_UNESCAPED_UNICODE));

// Conditional Query (Age greater than 30)
$cursor = $collection->find(['age' => ['$gt' => 30]]);
echo "Users with age greater than 30:\\n";
foreach ($cursor as $doc) {
printf(" - %s, Age: %d\\n", $doc['username'], $doc['age']);
}

// ========== Update Documents ==========
$result = $collection->updateOne(
['username' => 'jack'],
['$set' => ['age' => 32]]
);
printf("Updated %d documents\\n", $result->getModifiedCount());

// ========== Delete Documents ==========
$result = $collection->deleteMany([
'username' => ['$in' => ['jack', 'alice', 'bob']]
]);
printf("Deleted %d documents\\n", $result->getDeletedCount());

} catch (RuntimeException $e) {
printf("Operation failed: %s\\n", $e->getMessage());
}
Sample Output:
Inserted document ID: 6789abcdef1234567890abcd
Batch Insert 2 Documents
Query a single document: {"_id":"6789abcdef1234567890abcd","username":"jack","age":31,"email":"jack@example.com"}
Users with age greater than 30:
- jack, age: 31
- bob, age: 35
Update 1 Document
Delete 3 Documents

Method 2: Using the Underlying mongodb Extension

If the project does not use Composer, you can directly use the underlying MongoDB\\Driver API:
<?php
// Connection URI
$uri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin';
$manager = new MongoDB\\Driver\\Manager($uri);

// ========== Write Data ==========
$bulk = new MongoDB\\Driver\\BulkWrite;
$bulk->insert([
'username' => 'jack',
'age' => 31,
'email' => 'jack@example.com',
]);

// Write to the mydb.users collection
$writeConcern = new MongoDB\\Driver\\WriteConcern(MongoDB\\Driver\\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('mydb.users', $bulk, $writeConcern);
printf("Inserted %d documents\\n", $result->getInsertedCount());

// ========== Query Data ==========
$filter = ['username' => 'jack'];
$options = ['sort' => ['age' => -1]];
$query = new MongoDB\\Driver\\Query($filter, $options);
$rows = $manager->executeQuery('mydb.users', $query);

foreach ($rows as $row) {
print_r($row);
}

Must-Knows

Use a high-level library: The mongodb/mongodb Composer package provides a more user-friendly API and is recommended for new projects.
PHP Version: MongoDB PHP Library version 1.17 and above requires PHP 7.4 or later.
Connection Reuse: In a PHP-FPM environment, the MongoDB\\Client instance is automatically released after a request ends. When the MongoDB\\Client instance is used in a long-running process (such as Swoole), you should manage the connection pool.
BSON Types: In PHP, the MongoDB date type uses MongoDB\\BSON\\UTCDateTime, not the native PHP DateTime. The _id in query results is of type MongoDB\\BSON\\ObjectId.

FAQs

Authentication failed During Connection

Error Message Example:
MongoDB\\Driver\\Exception\\AuthenticationException: Authentication failed.
Troubleshoot by following these steps:
1. Confirm that the authentication database is specified as admin in the URI.
// Correct: The URI path is /admin.
$uri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin';
// Correct: Specify the authentication database via the authSource parameter when connecting to the business database.
$uri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb?authSource=admin';

// Error: When connecting to the business database without specifying authSource, the driver defaults to authenticating with the mydb database, causing authentication to fail.
$uri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/mydb';

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: PHP 8.3.6 (cli) (built: Jul 14 2025 18:30:55) (NTS)

2. Confirm that special characters in the password are URL-encoded: Use rawurlencode() to encode the password.
$password = rawurlencode('pass@123'); // Output: pass%40123
$uri = sprintf('mongodb://mongouser:%s@10.66.187.127:27017/admin', $password);

Running Environment

Operating System: Ubuntu 24.04.3 LTS / x86_64

Runtime Version: PHP 8.3.6 (cli) (built: Jul 14 2025 18:30:55) (NTS)

3. Confirm that the username and password are correct: Log in to the MongoDB console and verify the user information on the instance management page. If you forget the password, you can reset it in the console.

Class 'MongoDB\\Client' not found

Error Message Example:
PHP Fatal error: Uncaught Error: Class 'MongoDB\\Client' not found in /path/to/script.php
This error indicates that the MongoDB PHP Library is not installed correctly or is not loaded. Troubleshoot by following these steps:
1. Confirm that the underlying mongodb extension is installed: Run the following command to confirm that the extension is loaded:
php -m | grep mongodb
If mongodb is output, it indicates that the extension is installed.
If there is no output, install the extension:
pecl install mongodb
After the installation is complete, add the following to php.ini:
extension=mongodb.so
2. Confirm that the Composer package is installed. Run the following command to confirm that the mongodb/mongodb package is installed:
composer show mongodb/mongodb
If it is not installed, run the following command:
composer require mongodb/mongodb
3. Confirm that autoload.php is included: In your PHP script, confirm that the Composer autoload file is included at the top of the file:
<?php
require_once __DIR__ . '/vendor/autoload.php';

No suitable servers found or Connection Timeout

Error Message Example:
MongoDB\\Driver\\Exception\\ConnectionTimeoutException: No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling hello on '10.66.187.127:27017']
Troubleshoot by following these steps:
1. Confirm network connectivity: Run the following command on the CVM to verify whether the network is reachable:
telnet <MongoDB-instance-IP> 27017
The output Connected indicates that the network is reachable. Check the authentication configuration.
If the output is Connection timed out or Connection refused, it indicates a network connectivity issue. Confirm that the CVM and the MongoDB instance are in the same VPC and check the security group rules.
2. Check for differences between the PHP-FPM and CLI environments: PHP-FPM and CLI may use different php.ini configuration files. Please confirm that the mongodb extension is loaded in both environments:
# View the php.ini path for the CLI environment
php --ini

# View the configuration for the PHP-FPM environment (via phpinfo())
php -r "phpinfo();" | grep "Loaded Configuration File"

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백