zoukankan      html  css  js  c++  java
  • 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));

  • 相关阅读:
    文字溢出隐藏并以...展示
    定时器
    angular新建组件的组成部分
    angular五个常用语法
    element-ui 分页设置之低于10条显示完整分页页码
    new关键字执行过程
    js运用sort对json 数组进行排序
    正则验证积累
    jq监听
    gitHub命令大全
  • 原文地址:https://www.cnblogs.com/datastack/p/3854439.html
Copyright © 2011-2022 走看看