PHP7对mongodb的curd操作

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值