tencent cloud

TencentDB for MongoDB

Release Notes and Announcements
Release Notes
Announcements
User Guide
Product Introduction
Overview
Strengths
Use Cases
Cluster Architecture
Product Specifications
Features
Regions and AZs
Terms
Service Regions and Service Providers
Purchase Guide
Billing Overview
MongoDB Pricing
Billing Formula
Payment Overdue
Backup Space Billing
Configuration Adjustment Billing
Getting Started
Quickly Creating an Instance
Connecting to a TencentDB for MongoDB Instance
Reading/Writing Database
Operation Guide
Access Management
Instance Management
Node Management
Version Upgrade
Network Configuration
Monitoring
Backup and Rollback
Database Audit
Data Security
SSL Authentication
Log Management
Database Management
Multi-AZ Deployment
Disaster Recovery/Read-Only Instances
Parameter Configuration
Recycle Bin
Task Management
Performance Optimization
Data Migration Guide
Practical Tutorial
Optimizing Indexes to Break Through Read/Write Performance Bottlenecks
Troubleshooting Mongos Load Imbalance in Sharded Cluster
Considerations for Using Shard Clusters
Sample of Reading and Writing Data in MongoDB Instance
Methods for Importing and Exporting Data Based on CVM Connected with MongoDB
What to Do for Errors of Repeated Instance Creation and Deletion of Databases with the Same Names?
Troubleshooting MongoDB Connection Failures
Shard Removal Task: Guide for Confirming the Progress and Troubleshooting Issues
Performance Fine-Tuning
Ops and Development Guide
Development Specifications
Command Support in Sharded Cluster v3.2
Command Support in v3.6
Development Ops
Troubleshooting
Increased Slow Queries
Number of Connections Exceeding Limit
API Documentation
History
Introduction
API Category
Making API Requests
Instance APIs
Backup APIs
Account APIs
Other APIs
Task APIs
Introduction
Data Types
Error Codes
Instance Connection
Shell Connection Sample
PHP Connection Sample
Node.js Connection Sample
Java Connection Sample
Python Connection Sample
Python Read/Write Sample
Go Connection Sample
PHP Reconnection Sample
Product Performance
Test Environment
Test Method
Test Result
FAQs
Cost
Features
Sharded Cluster
Instance
Rollback and Backup
Connection
Data Migration
Others
Service Agreement
Service Level Agreement
Terms of Service
Glossary
Contact Us

PHP Connection Sample

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2024-01-15 14:49:56

Notes

TencentDB for MongoDB provides two usernames rwuser and mongouser by default to support the MONGODB-CR and SCRAM-SHA-1 authentication methods, respectively. The connecting URIs for the two authentication methods are formed differently. For more information, please see Connecting to TencentDB for MongoDB Instance.
For PHP, there is a driver that can be used to connect to and manipulate a MongoDB database, namely, MongoDB driver. The MongoDB driver is officially recommended by MongoDB, but it requires PHP 5.4 or above.
The following shows you how to connect to TencentDB for MongoDB and read/write data by using the aforementioned driver.

Using MongoDB driver

For more information on how to install the MongoDB driver, please see Installation. The MongoDB driver can use both the MONGODB-CR and SCRAM-SHA-1 authentication methods. For more information, please see Connection Sample.
Sample code:
<?php
// Splice the connection URI
$uri = 'mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin';
$manager = new MongoDB\\Driver\\Manager($uri);

// Prepare to write data
$document1 = [
'username' => 'lily',
'age' => 34,
'email' => 'lily@qq.com'
];

// Preprocess the data with the driver. Here, you can see that `_id` of MongoDB is generated by the driver
$bulk = new MongoDB\\Driver\\BulkWrite;
$_id1 = $bulk->insert($document1);

$result = $manager->executeBulkWrite('tsdb.table1', $bulk);

// You can also use the following code as needed to ensure that data is written to a majority of nodes
// $writeConcern = new MongoDB\\Driver\\WriteConcern(MongoDB\\Driver\\WriteConcern::MAJORITY, 1000);
// $result = $manager->executeBulkWrite('testdb.testcollection', $bulk, $writeConcern);

// Query
$filter = ['_id' => $_id1];
$query = new MongoDB\\Driver\\Query($filter);
$rows = $manager->executeQuery('tsdb.table1', $query); // You can also select to read a secondary database first
foreach($rows as $r){
print_r($r);
}


Output:
stdClass Object
(
[_id] => MongoDB\\BSON\\ObjectID Object
(
[oid] => 582c001618c90a16363abc31
)

[username] => lily
[age] => 34
[email] => lily@qq.com
)

Using PHPLIB library (encapsulated based on MongoDB driver)

We recommend you use PHPLIB with the MongoDB driver. For more information, please see CRUD Operations. For more information on how to install PHPLIB, please see Install the MongoDB PHP Library. Please note that PHPLIB depends on the MongoDB driver.
Sample code:
<?php
require_once __DIR__ . "/vendor/autoload.php";

// Initialize
$mongoClient = new MongoDB\\Client('mongodb://mongouser:thepasswordA1@10.66.187.127:27017/admin');

// Use the `users` collection under the `demo` library
$collection = $mongoClient->demo->users;

// Write a data entry
$insertOneResult = $collection->insertOne(['name' => 'gomez']);

printf("Inserted %d document(s)\\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());

// Query data
$document = $collection->findOne(['name' => 'gomez']);

var_dump($document);

Output:
Inserted 1 document(s)
object(MongoDB\\BSON\\ObjectID)#11 (1) {
["oid"]=>
string(24) "57e3bf20bf605714a53e69c1"
}
object(MongoDB\\Model\\BSONDocument)#16 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["_id"]=>
object(MongoDB\\BSON\\ObjectID)#14 (1) {
["oid"]=>
string(24) "57e3bf20bf605714a53e69c1"
}
["name"]=>
string(5) "gomez"
}
}


Ajuda e Suporte

Esta página foi útil?

comentários