[PHP]新版的mongodb擴展安裝和使用

舊版的mongo擴展已經不推薦使用了,在php7以上通常是安裝和使用新版的mongodb擴展php

ubuntu下mongodb

apt-get install php-mongodbubuntu

例以下面的代碼進行了查詢和插入集合操做php7

<?php
class DocModel{
    public $mongoManger=null;
    public $dbName='coms';
    public function __construct(){
        // 鏈接到mongodb
        $this->mongoManger = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
    }
    //添加文檔模型
    public function addModel($isDraft=false){
        $params=[];
        $params['modelID']='basic_news';
        $params['name']='基礎新聞';
        $params['parentID']='root';
        $params['modelXML']="<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<model>\r\n\t  <fields>\r\n\t  <field label=\"標題\" name=\"title\" type=\"string\" widget=\"title\" required=\"1\" maxLength=\"60\" minLength=\"1\"   esAnalyzed=\"analyzed\" esAddNoAnalyzed=\"yes\" >\r\n\t\t<widgetParams>\r\n\t\t\t<param name=\"marks\" value=\"5,13.5,40\"\/>\r\n\t\t<\/widgetParams>\r\n\t\t<validation>\r\n\t\t\t<rule type=\"maxZhLength\" value=\"40\" msgZh=\"標題長度不能超過40個漢字長度\" \/>\r\n\t\t<\/validation>\r\n\t<\/field>\r\n\t\t  <\/fields>\r\n  <layout>\r\n\t<fieldset name=\"basic\" legend=\"基本信息\">\r\n\t\t<field name=\"title\" width=\"12\"\/>\r\n\t<\/fieldset>\t\r\n  <\/layout>\r\n<\/model>";
        $params['isTest']='0';
        $params['desc']='shihan添加';
        $params['auditFeedback']='';
        $params['status']='1';
       $params['audited']='1';
       $collect=$isDraft ? '.modelDraft':'model';

        $bulk = new MongoDB\Driver\BulkWrite();
        $sets= ['$set' => $params];
        $bulk->update(['modelID' => $params['modelID']],$sets, ['multi' => false, 'upsert' => true]);
        $this->mongoManger->executeBulkWrite($this->dbName.$collect, $bulk);
    }
    //文檔模型列表
    public function listModel($isDraft=false){
        $filter = [];
        $options = [];
        $collect=$isDraft ? '.modelDraft':'model';
        $query = new MongoDB\Driver\Query($filter, $options);
        $cursor = $this->mongoManger->executeQuery($this->dbName.$collect, $query);
        foreach ($cursor as $document) {
            var_dump($document);
        }
    }
    //獲取文檔模型詳情
    public function getModel($isDraft=false){
        $params['modelID']='basic_news';
        $filter = ['modelID'=>$params['modelID']];
        $options = [];
        $collect=$isDraft ? '.modelDraft':'model';
        $query = new MongoDB\Driver\Query($filter, $options);
        $cursor = $this->mongoManger->executeQuery($this->dbName.$collect, $query);
        foreach ($cursor as $document) {
            var_dump($document);
        }
    }
}
$docModel=new DocModel();
$docModel->getModel(true);
相關文章
相關標籤/搜索