mongodb php 增删改查

来源:互联网 发布:java接收post请求数据 编辑:程序博客网 时间:2024/05/18 22:14
  1. $mongo = new Mongo();  
  2. $db = $mongo->selectDB('test');  
  3. $collection = $db->selectCollection('foo');  
  4.   
  5.   
  6. //插入  
  7. $array = array('name'=>'张三','sex'=>'male');  
  8. $bool = $collection->insert($array);  
  9.   
  10. //更新  
  11. $where = array('name'=>'张三');  
  12. $newdata = array('name'=>'张三','sex'=>'female');  
  13. $bool = $collection->update($where,array('$set',$newdata));  
  14.   
  15.   
  16. //批量更新  
  17. $where = array('y'=>'9');  
  18. $newdata = array('y'=>10);  
  19. $bool = $collection->update($where,array('$set'=>$newdata),array("multiple" => true));  
  20.   
  21. //删除字段  
  22. $where = array('a'=>'1');  
  23. $bool = $collection->update(array('b'=>'t'),array('$unset'=>array('c'=>1)));  
  24. echo '<pre>';var_dump($bool);exit;  
  25.   
  26. //$push  
  27. $bool = $collection->update(array('a'=>'1'),array('$push'=>array('c'=>'wow')));  
  28. echo '<pre>';var_dump($bool);exit;  
  29.   
  30. //删除文档  
  31. $where = array('name'=>'张三');  
  32. $bool = $collection->remove($where);  
  33.   
  34.   
  35. //group  
  36. $keys = array("category" => 1);  
  37. $initial = array("count" => 0);  
  38. $reduce = "function (obj, prev) { prev.count++ }";  
  39.   
  40. $condition = array('condition' => array('category' => array'$exists' => 1)));  
  41.   
  42. $g = $collection->group($keys$initial$reduce$condition);  
  43. echo '<pre>';print_r($g);exit;  
  44.   
  45.   
  46. //distinct  
  47. $retval = $collection->distinct("zip-code",array('stuff'=>'foo'));  
  48.   
  49.   
  50.   
  51.   
  52. //查询,sort  
  53. $where = array('y'=>array('$exists'=>true,'$gte'=>5,'$lt'=>10));  
  54. $result = $collection->find($where)->sort(array('y'=>-1));  
  55. $arr = array();  
  56. foreach($result as $key=>$value){  
  57.         $arr[] = $value;  
  58. }  
  59.   
  60. echo '<pre>';print_r($arr);

  61. 在一个集合中计算文档的数量

    现在我们插入了101个文档(我们用循环插入了100个,之前还插入了一个),我们可以使用count()来看看我们的数据是不是都被插入进去了

    <?php
    echo $collection->count();
    ?>
     

    我们同样可以得到20 < i <= 30之间的数据

    <?php$query = array( “i” => array( “\$gt” => 20, “\$lte” => 30 ) );
    $cursor = $coll->find( $query );
    while( $cursor->hasNext() ) {
        var_dump( $cursor->getNext() );
    }
  62. 建一个索引
  63. MongoDB支持索引,并且可以很容易的加到一个集合中,你只要指定某个字段为索引就行了,并且还可以指定 正序索引(1)与 倒序索引(-1)
    下面的代码为I创建了索引

    复制代码代码如下:
    <?php
    $coll->ensureIndex( array( “i” => 1 ) );  //在”i”上创建了一个索引
    $coll->ensureIndex( array( “i” => -1, “j” => 1 ) );//在”i”上创建了倒序索引 在”j”上创建了正序索引

0 0