PHP Connection Sample

Last updated: 2020-04-26 17:57:58

    Notes

    TencentDB for MongoDB provides two usernames rwuser and mongouser by default to support the MONGODB-CR and SCRAM-SHA-1 authentication methods, respectively, which have different configurations for URI connection. For more information, please see Connecting to Instances.

    For PHP, there are two drivers that can be used to connect to and manipulate a MongoDB database, namely:

    • MongoDB (MongoDB driver): the MongoDB driver is officially recommended by MongoDB, but it requires PHP 5.4 or above.
    • Mongo (MongoDB driver (legacy)): Mongo is a legacy driver but can still be used. If you want to use it, please choose v1.6.

    The following samples show you how to connect to TencentDB for MongoDB and read and write data by using the abovementioned drivers.

    Using the MongoDB driver

    For more information on how to install MongoDB, please see Installation.
    The MongoDB driver can use both the MONGODB-CR and SCRAM-SHA-1 authentication methods. For more information, please see Connecting to Instances.

    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 slave 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 the Mongo driver

    The Mongo driver supports only the MONGODB-CR authentication method and can use only the username rwuser for connection. For more information, please see Connecting to Instances.

    Sample code:

    <?php
    // You are recommended to use either of the following URIs for connection
    $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);
    
    /*
    // Alternatively, you can use the following code
    $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);

    Using PHPLIB library (encapsulated based on MongoDB driver)

    You are recommended to 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";
    
    // Initialization
    $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"
      }
    }
    

    Was this page helpful?

    Was this page helpful?

    • Not at all
    • Not very helpful
    • Somewhat helpful
    • Very helpful
    • Extremely helpful
    Send Feedback
    Help