php操作mongodb基础语法

一、插入数据

 1 <?php
 2     
 3     //连接Mongodb
 4     $manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
 5     
 6     echo "connect success!!!";
 7     
 8     //创建变量,进行插入操作
 9     $bulk = new MongoDB\Driver\BulkWrite;
10     
11     //插入的数据(插入一条或多条)
12     $bulk->insert(["name"=>"zhangsan","age"=>25,"class"=>"jisuanjierban"]);
13     $bulk->insert(["name"=>"lisi","age"=>25,"class"=>"jisuanjisiban"]);
14     
15     //插入数据到useinfo数据库下的student表
16     $manager->executeBulkWrite("useinfo.student",$bulk);
17     
18     echo "insert success!!!";
19 ?>

二、查询数据

 1 <?php
 2  
 3     //连接Mongodb
 4     $manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
 5     
 6     echo "connect success!!!".PHP_EOL;
 7     
 8     //过滤条件
 9     $filter  = ['age' => ['$gt' => 20]];
10     
11     //可选项
12     $option = [
13         
14         'projection' => ["_id" =>0],  //不显示_id,此字段用于指定显示或不显示某些字段
15         
16         'sort' => ['name' => -1],     //按照某些字段排序 ,-1倒叙,1正序
17         
18         'limit'=>$pageSize,  //取多少条数据
19         
20         'skip' => ($num-1)*$pageSize  //取第几页数据
21     ];
22     
23     //查询数据
24     $query = new MongoDB\Driver\Query($filter, $option);
25     
26     //查询结果,返回数组
27     $cursor = $manager->executeQuery('useinfo.student',$query);
28     
29     //循环遍历
30     foreach ($cursor as $document){
31     
32         print_r($document);
33     }
34     
35     echo "over";
36     
37 ?>

三、更新数据

 1 //更新数据
 2 <?php 
 3     //连接Mongodb
 4     $manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
 5     
 6     echo "connect success!!!"
 7     
 8     $bulk->new MongoDB\Driver\BulkWrite;
 9     $bulk->update(
10         ["name" => "zhangsan"],   //过滤条件
11         ["$set" => ["name" => "kenan","class" => "softeneregy"]], //更新数据
12         ["multi" => false, "upsert" => false],  //multi为true,代表更新找到的所有记录,false默认更新找到的第一条
13                                                 //upsert为true代表如果没有此条记录就执行插入操作,默认false不插入
14     );
15     //执行更新操作
16     $result = $manager->executeBulkWrite('test.sites', $bulk);
17 ?>

 

上一篇:用自定义定界符和C#中一些非常大的字段值解析文本的最快方法是什么?


下一篇:Spring Boot 项目学习 (一) 项目搭建