PHP 操作Mongodb 实例

php7 mongoDb 操作

1. php7 mongoDb 的安装

windows10 安装

linux安装

2. PHP 与 mongoDb 的链接

$database = 'test';// 数据库名字
$table = 'sites';// 集合名字  mysql 的表名字

//mongodb://localhost:27017  自己的端口
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

3. 操作

$bulk = new MongoDB\Driver\BulkWrite;   //创建一个操作类(可用来批量 修改 添加  删了)

//1. 批量添加
$_id= $bulk->insert(['goods_id' => 1, 'name' => '哈哈1']);
$_id= $bulk->insert(['goods_id' => 2, 'name' => '哈哈2']);
$_id= $bulk->insert(['goods_id' => 3, 'name' => '哈哈3']);


// 2. 批量修改  第一个参数为条件  第二个字段为修改的字段
//$_id= $bulk->update(['goods_id' => 1],['name' => '修改1']);
//$_id= $bulk->update(['goods_id' => 2],['name' => '修改2']);

//  3. 批量删除    第一个参数为条件
//$_id= $bulk->delete(['goods_id'=>1],['limit'=>0]); // limit 为 0 时,删除所有匹配数据  
//$_id= $bulk->delete(['goods_id'=>2],['limit'=>1]); // limit 为 1 时,删除第一条匹配数据
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite($database.'.'.$table, $bulk, $writeConcern);

4. 普通查询

//普通查询 (Query)
$filter = ['goods_id'=>1];  //等于的写法      具体请看下面($filter) 的写法
$options = [];        // 具体请看下面($options)的参数

// 查询数据
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery($database.'.'.$table, $query);
var_dump($cursor->toArray());

($filter) 的写法

$filter = [];  //查全部
$filter = ['goods_id'=>['$lt'=>10]];  //小于写法
$filter = ['goods_id'=>['$lte'=>10]];  //小于等于写法
$filter = ['goods_id'=>['$gt'=>1]];  //大于写法
$filter = ['goods_id'=>['$gte'=>1]];  //大于等于写法
$filter = ['goods_id'=>['$ne'=>1]];  //不等于写法
$filter = ['goods_id'=>['$in'=>[1,2,3]]];  //in  写法
$filter = ['goods_id'=>['$nin'=>[1,2,3]]];  //not in  写法
$filter = ['goods_id'=>['$lt'=>10],'goods_name'=>'哈哈'];  //AND 写法
$filter = ['$or'=>[['goods_id'=>['$lt'=>10],'name'=>'哈哈3']]];  //OR 写法
$filter = ['$or'=>[['goods_id'=>['$lt'=>10]]],'name'=>'哈哈3'];  //OR & AND 写法

 

($options)的参数

$options = [
    'projection' => ['_id' => 0 , 'goods_id' => 1 , 'name' => 1],  //显示的字段  0不显示   1显示
    'sort' => ['goods_id' => -1],   //-1 == 倒序   1正序
    'limit' => 10,  //显示多少条
    'skip' => 0,  //跳过多少条
];

//可以使用  limit + skip 实现分页

以上就是基本的mongoDb 的操作了 如有问题请留言作者
作者: Quan

联系方式:
邮箱: 846951943@qq.com
Q Q: 846951943

posted @ 2021-08-02 11:57  &权  阅读(425)  评论(0编辑  收藏  举报