百度BAE 平台PHP对Mongodb的连接

<?php
 
 
/*请替换为你自己的数据库名(可从管理中心查看到)*/
$dbname = 'XgmsRXDEYIDGmQFCjaZl';
 
/*从环境变量里取host,port,user,pwd*/
$host = getenv('HTTP_BAE_ENV_ADDR_MONGO_IP');
$port = getenv('HTTP_BAE_ENV_ADDR_MONGO_PORT');
$user = getenv('HTTP_BAE_ENV_AK');
$pwd = getenv('HTTP_BAE_ENV_SK');
 
try {
    /*建立连接后,在进行集合操作前,需要先select使用的数据库,并进行auth*/
    $mongoClient = new MongoClient("mongodb://{$host}:{$port}");
    $mongoDB = $mongoClient->selectDB($dbname);
    $mongoDB->authenticate($user, $pwd);
 
    /*接下来就可以对该库上的集群进行操作了,具体操作方法请参考php-mongodb官方文档*/
    $mongoCollection = $mongoDB->selectCollection('test');
    $array = array(
        'key1' => 'value1',
    );
    $ret = $mongoCollection->insert($array);
    $mongoCursor = $mongoCollection->find();
    while($mongoCursor->hasNext()) {
        print_r($mongoCursor->getNext());
    }
} catch (Exception $e) {
    die($e->getMessage());
}
 
?>

  来自bae的doc文档。

posted @ 2013-07-31 15:34  r3call  阅读(1051)  评论(0编辑  收藏  举报