💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
>[info] 安装mongodb工具 Robo 3T 下载地址:https://robomongo.org/ 连接 mongodb: ![](https://img.kancloud.cn/01/d8/01d88761d78f562d5e57b0e0c63ea8f5_1946x1281.png) >[info] php7操作mongodb示例 **注:** 首先安装 mongodb 扩展 **PHP7 连接 MongoDB 语法如下:** ~~~ $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); ~~~ ### **1. 插入数据** ~~~ <?php // 连接 $manager = new MongoDB\Driver\Manager("mongodb://192.168.83.130:27017"); // 插入 $bulk = new MongoDB\Driver\BulkWrite; $bulk->insert(['x' => 1, 'name'=>'hello', 'url' => 'http://www.hello.com']); $bulk->insert(['x' => 2, 'name'=>'aaa', 'url' => 'http://www.aaa.com']); $bulk->insert(['x' => 3, 'name'=>'bbb', 'url' => 'http://www.bbb.com']); $manager->executeBulkWrite('testdb.test1', $bulk); // (>) 大于 - $gt // (<) 小于 - $lt // (>=) 大于等于 - $gte // (<= ) 小于等于 - $lte $filter = ['x' => ['$gt' => 1]]; $options = [ 'projection' => ['_id' => 0], // sort() 方法可以通过参数指定排序的字段,其中 1 为升序排列,而 -1 是用于降序排列。 'sort' => ['x' =>1], ]; // 查询 $query = new MongoDB\Driver\Query($filter, $options); $cursor = $manager->executeQuery('testdb.test1', $query); foreach ($cursor as $document) { print_r($document); } ~~~ **运行效果:** ![](https://img.kancloud.cn/2b/6b/2b6b44b770c25d81c66a390d1fb7bcde_705x556.png) ### **2. 更新数据** ~~~ <?php // 更新 $bulk = new MongoDB\Driver\BulkWrite; $bulk->update( ['x' => 2], ['$set' => ['name' => 'winner', 'url' => 'tool.hello.com']], ['multi' => false, 'upsert' => false] ); // 连接 $manager = new MongoDB\Driver\Manager("mongodb://192.168.83.130:27017"); $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); // 执行更新 $result = $manager->executeBulkWrite('testdb.test1', $bulk, $writeConcern); var_dump($result); ~~~ **运行效果:** ![](https://img.kancloud.cn/9e/f2/9ef229144d024a2a5225f607eec28cae_785x577.png) ![](https://img.kancloud.cn/3c/34/3c342e65fc8fb567265b63bdb4079f1c_1395x590.png) ### **3. 删除数据** ~~~ <?php // 实例化操作 $bulk = new MongoDB\Driver\BulkWrite; $bulk->delete(['x' => 1], ['limit' => 1]); // limit 为 1 时,删除第一条匹配数据 $bulk->delete(['x' => 2], ['limit' => 0]); // limit 为 0 时,删除所有匹配数据 $manager = new MongoDB\Driver\Manager("mongodb://192.168.83.130:27017"); $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); // 执行删除 $result = $manager->executeBulkWrite('testdb.test1', $bulk, $writeConcern); var_dump($result); ~~~ **运行效果:** ![](https://img.kancloud.cn/a1/d6/a1d66f45e32d0e7b149fd0a30c3a0786_874x603.png) ![](https://img.kancloud.cn/d1/bf/d1bfdb41262d70ba4227ca49c34a4bcb_1481x411.png)