PHP Connection Sample

Last updated: 2019-08-12 11:34:36

PDF

Description

By default, TencentDB for MongoDB provides two user names "rwuser" and "mongouser" for the "MONGODB-CR" and "SCRAM-SHA-1" authentication methods respectively. The URI connection between these two authentication methods is different. For more information, see Connection Example.

In PHP, two sets of drivers can be used to connect to and operate on MongoDB:

Below demonstrates how to connect to and perform read and write operations on TencentDB for MongoDB using the drivers mentioned above.

Use the mongodb driver

To learn how to install mongodb, see installation steps on the official website.
The mongodb driver supports both MONGODB-CR and SCRAM-SHA-1 authentication. For more information, see Connection Example.

Sample code:

<?php
// Form 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'
];

// The driver pre-processes data. You can find that the "_id" of MongoDB is generated by the driver.
$bulk = new MongoDB\Driver\BulkWrite;
$_id1 = $bulk->insert($document1);

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

// Or include the following codes when necessary to ensure the data is written to most 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 choose to read data from the slave database first. For more information, see relevant documentation.
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
)

Use the mongo driver

The mongo driver only supports MONGODB-CR authentication method and thus only "rwuser” is valid for this connection. For more information, see Connection Example.

Sample code:

<?php
// It is recommended to use URI for connection. Either of the two URIs is OK.
$uri = "mongodb://rwuser:thepasswordA1@10.66.187.127:27017/admin?authMechanism=MONGODB-CR";
$uri = "mongodb://rwuser:thepasswordA1@10.66.187.127:27017/?authMechanism=MONGODB-CR&authSource=admin";
$connection = new MongoClient($uri);

/*
// Or you can use the following codes.
$connection = new MongoClient("mongodb://10.66.116.103:27017/admin",
    array(
        "username" => "rwuser",
        "password" => "password",
        "authMechanism" => "MONGODB-CR"
    )
);
*/
$db = $connection->tsdb;
$collection = $db->table1;

$q = array(
    'id' => 1,
    'test1' => 'xxx',
    'ss' => 'xxxxxxxx',
);
$collection->save($q);
$one = $collection->findOne();
var_dump($one);

It is recommended to use the mongodb driver together with PHPLIB. For more information, see relevant documentation.
For more information on how to install PHPLIB, see installation steps on the official website. Note that PHPLIB depends on the mongodb driver.

Sample code:

<?php
require_once __DIR__ . "/vendor/autoload.php";

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

// Use the "users" collection under the "demo" database
$collection = $mongoClient->demo->users;

// Write a piece of data
$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"
  }
}