Thinkphp 操作mongodb数据库的增删改查

首先安装 mongodb扩展

<?php

namespace app\admin\model;
use think\Model;

class Monmodel extends Model 
{
    public $dbName ='moba_game';//(要连接的数据库名称)

    public $manager;

    public function __construct()
    {
        $this->manager = new \MongoDB\Driver\Manager("mongodb://账号:密码@Ip地址:27017");
       
    }

    /**
     * 查询数据
     * name 查询的表名 
     * filter   
     * options
    */
    public function Looktable($name ,$filter = [], $options = [] )
    {
        $block = $this->dbName .'.'. $name;
        $query = new \MongoDB\Driver\Query($filter, $options);
        $cursor = $this->manager->executeQuery($block, $query);
        return $cursor;
    }

    /**
     * 插入数据
     * name 块名
     * array 插入的数据
    */
    public function Inserttable($name , $array)
    {
        $bulk = new \MongoDB\Driver\BulkWrite;
        $block = $this->dbName .'.'. $name;
        $bulk->insert($array);
		$result = $this->manager->executeBulkWrite($block, $bulk);
        return $result;
    }

    /**
     * 删除数据
    */
    public function deleteTable($name , $array)
    {
        $bulk = new \MongoDB\Driver\BulkWrite;
        $block = $this->dbName .'.'. $name;
        $bulk->delete($array);
        $result = $this->manager->executeBulkWrite($block, $bulk);
        return $result;
    }

    /**
     * 修改数据
    */
    public function updateTable($name , $where , $newdata)
    {
        $bulk = new \MongoDB\Driver\BulkWrite;
       $block = $this->dbName .'.'. $name;

       $bulk->update($where, array('$set' => $newdata), array('multi' => false, 'upsert' => false));
        $result = $this->manager->executeBulkWrite($block, $bulk);
        return $result;
    }

    /**
    *  插入数据的时候  获取到目前Id 应该的值
    */
    public function max_returnId()
    {
        //过滤条件
        // $filter  = ['age' => ['$gt' => 20]];
        $filter = [];

        //可选项
        $option = [
            
            'projection' => ["_id" =>0],  //不显示_id,此字段用于指定显示或不显示某些字段
            
            'sort' => ['Id' => -1],     //按照某些字段排序 ,-1倒叙,1正序
            
            'limit'=>1,  //取多少条数据

            // 'skip' => ($num-1)*$pageSize  //取第几页数据
            
        ];
        
        //查询数据
        $query = new \MongoDB\Driver\Query($filter, $option);

        //查询结果,返回数组
        $cursor = $this->manager->executeQuery('moba_game.shopGoods',$query);

        foreach ($cursor as $document){

            return $document->Id + 1;

        }

    }

}

增删改查都有了  目前在做求和 各种更详细的操作

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值