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 |
pecl install mongodb
php.ini:extension=mongodb.so
composer require mongodb/mongodb
<?phprequire_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());}
Inserted document ID: 6789abcdef1234567890abcdBatch Insert 2 DocumentsQuery a single document: {"_id":"6789abcdef1234567890abcd","username":"jack","age":31,"email":"jack@example.com"}Users with age greater than 30:- jack, age: 31- bob, age: 35Update 1 DocumentDelete 3 Documents
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);}
mongodb/mongodb Composer package provides a more user-friendly API and is recommended for new projects.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.MongoDB\\BSON\\UTCDateTime, not the native PHP DateTime. The _id in query results is of type MongoDB\\BSON\\ObjectId.MongoDB\\Driver\\Exception\\AuthenticationException: Authentication failed.
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';
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: PHP 8.3.6 (cli) (built: Jul 14 2025 18:30:55) (NTS)
rawurlencode() to encode the password.$password = rawurlencode('pass@123'); // Output: pass%40123$uri = sprintf('mongodb://mongouser:%s@10.66.187.127:27017/admin', $password);
Operating System: Ubuntu 24.04.3 LTS / x86_64
Runtime Version: PHP 8.3.6 (cli) (built: Jul 14 2025 18:30:55) (NTS)
PHP Fatal error: Uncaught Error: Class 'MongoDB\\Client' not found in /path/to/script.php
mongodb extension is installed: Run the following command to confirm that the extension is loaded:php -m | grep mongodb
mongodb is output, it indicates that the extension is installed.pecl install mongodb
php.ini:extension=mongodb.so
mongodb/mongodb package is installed:composer show mongodb/mongodb
composer require mongodb/mongodb
autoload.php is included: In your PHP script, confirm that the Composer autoload file is included at the top of the file:<?phprequire_once __DIR__ . '/vendor/autoload.php';
MongoDB\\Driver\\Exception\\ConnectionTimeoutException: No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling hello on '10.66.187.127:27017']
telnet <MongoDB-instance-IP> 27017
Connected indicates that the network is reachable. Check the authentication configuration.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.php.ini configuration files. Please confirm that the mongodb extension is loaded in both environments:# View the php.ini path for the CLI environmentphp --ini# View the configuration for the PHP-FPM environment (via phpinfo())php -r "phpinfo();" | grep "Loaded Configuration File"
피드백