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,布布扣,bubuko.com

PHP使用Mongodb

上一篇:SQL Server 执行计划中的扫描方式举例说明


下一篇:(转) 如何向SQL Server 2005中插入中文