mongodb php增删改查基本操作

 
  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 '
    ';var_dump($bool);exit;  
  25.   
  26. //$push  
  27. $bool = $collection->update(array('a'=>'1'),array('$push'=>array('c'=>'wow')));  
  28. echo '
    ';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 '
    ';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 '
    ';print_r($arr);  
 
 
 
原文地址:https://www.cnblogs.com/myJuly/p/10008513.html