PHP实现对MongoDB的基础操作

PHP扩展                                                                                     

PHP5.2、PHP5.3,线程、非线程,IIS、Apache综合下载地址:

http://pan.baidu.com/s/1sjrW6z7

下载相对应的php扩展文件php_mongo.dll,拷入php扩展文件夹里/php/ext,修改php.ini文件,新增下列行:

extension=php_mongo.dll

PHP操作                                                                                     

  • 连接数据库
$conn = new Mongo("mongodb://localhost:27017//admin:admin");
  • 选择数据库和集合
//选择数据库blog,如果没有,则创建

$db = $conn->yyd;

//也可以写成:$db = $conn->selectDB('yyd');


//制定结果集(集合:yyd_test)
$collection = $db->yyd_test;

//也可以写成:$collection = $db->selectCollection('yyd_test');
//var_dump($collection);
  • 新增数据
$post = array('name' => '22', 'sex' => '32');

$flag=($collection->insert($post));
var_dump($flag);

image

image

  • 查找数据
$arr=array();
$cursor = $collection->find($arr);
foreach($cursor as $key => $value){
    echo "<pre>";
    echo $value['_id'];
    echo '<br>name:';
    echo $value['name'];
    echo "<br>sex:";
    echo $value['sex'];
    echo "</pre>";
}

image

  • 条件查找
$arr=array("name"=>"22");
$cursor = $collection->find($arr);
  • 修改数据

image

$newdata = array('$set' => array("email" => "test@test.com"));
$collection->update(array("name" => "22"), $newdata);
var_dump($collection);

$arr=array("name"=>"22");
$cursor = $collection->find($arr);
foreach($cursor as $key => $value){
    echo "<pre>";
    echo $value['_id'];
    echo '<br>name:';
    echo $value['name'];
    echo "<br>sex:";
    echo $value['sex'];
    echo "<br>email:";
    echo $value['email'];
    echo "</pre>";
}
  • 删除数据

image

$arr=array("name"=>"22");

$collection->remove($arr);

var_dump($collection);

image

  • 其它常用操作
//关闭连接

$conn->close();


//删除一个数据库

$conn->dropDB("yyd");


//列出所有可用数据库

$dbs = $conn->listDBs();

 

带有MongoDB操作函数的的PHP手册:

http://pan.baidu.com/s/1pJz2llh

或者网站:

http://www.php.net/manual/zh/class.mongodb.php

 

 

 

转载请注明出处:http://www.cnblogs.com/yydcdut/p/3571430.html

posted @ 2014-02-28 12:49  我爱物联网  阅读(1566)  评论(0编辑  收藏  举报
AmazingCounters.com