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 '<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);  

转载于:https://my.oschina.net/u/588516/blog/1594924

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值