PHP使用Mongodb

一.安装Mongodb的PHP扩展

wget http://pecl.php.net/get/mongo-1.2.7.tgz //下载扩展包
tar zxvf mongo-1.2.7.tgz
cd mongo-1.2.7
/usr/local/php/bin/phpize
./configure -with-php-config=/usr/local/php/bin/php-config
make

make install

注:当在ubuntu环境下,需要root权限,需要加sudo ,故sudo make && make install 会报ERROR,应该是 sudo make && sudo make install 才行,因为make install也需要root权限才行。

 

二、Mongodb 的CRUD API

1.连接Mongodb 获取集合

$conn = new MongoClient("mongodb://127.0.0.1:27017");
$db = $conn->mydb;
$collection = $db->user;

 

2.Insert 操作

$u1 = array(‘id‘=>216,‘name‘=>‘wfm11‘,‘age‘=>121,‘addr‘=>‘2beijing‘);
$result = $collection->insert($u1);
echo ‘new user u1:‘.$u1[‘_id‘].‘<br>‘;

 

3.Update操作

$re = $collection->update($where = array(‘id‘=>1),array(‘set‘=>array(‘id‘=>1,‘name‘=>‘aaa‘,‘addr‘=>‘hangzhou‘)));

 

4.Select 操作

$cursor = $collection->find()->snapshot();
foreach($cursor as $id => $value){
  echo $id.‘:‘.$value[‘id‘].‘--->‘.$value[‘name‘];
  var_dump($value);
}

 

$cursor = $collection->find(array(‘id‘=>array(‘$gt‘=>0,‘$lte‘=>21)));
while($cursor->hasNext()){
 var_dump($cursor->getNext());
}

 

$doc = $collection->findOne();
var_dump($doc);

 

5.count 操作

echo ‘count:‘.$collection->count().‘<br>‘;
echo ‘id=1 count‘.$collection->count(array(‘id‘=>1)).‘<br>‘;

 

6.remove操作

$re = $collection->remove(array(‘id‘=>269));

 

7.添加索引,指定排序规则

//add index on name (asc),age(desc)
$collection->ensureIndex(array("name" => -1,"age"=>1));

PHP使用Mongodb,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。