Smart.Framework Logo

final class \SmartMongoDb
{ } ->

Class Smart MongoDB Client (for PHP MongoDB extension v.1.1.0 or later)
Tested and Stable on MongoDB Server versions: 3.2 / 3.4 / 3.6 / 4.0 / 4.1 / 4.2 / 4.3 / 4.4 / 5.0 / 5.1 / 5.2


class Methods

public function __construct ( array $y_configs_arr = [], bool $y_fatal_err = true ) {} @ 
@throws: {Exception} Depending how this class it is constructed it may throw Exception or Raise Fatal Error
@param: {ARRAY} $y_configs_arr: *Optional* ; The Array of Configuration parameters ; Default is Empty Array, case which will get the configuration from config.php ; if custom, the ARRAY STRUCTURE should be identical with the default config.php: $configs['mongodb'].
@param: {BOOLEAN} $y_fatal_err: *Optional* ; Set if Errors handling mode ; Default is TRUE ; if set to FALSE will throw Exception instead of Raise a Fatal Error
Class constructor
public function assign_uuid ( ) {} -> STRING
@return: {STRING} UUID (base36)
A replacement for the default MongoDB object ID, will generate a 32 characters very unique UUID
public function get_ext_version ( ) {} -> STRING
@return: {STRING} MongoDB extension version
Get the MongoDB Extension version
public function get_server_version ( ) {} -> STRING
@return: {STRING} MongoDB version
Get the MongoDB server version
public function setFatalErrMode ( bool $is_fatal ) {} -> VOID
@return: {VOID}
Set Fatal Error Mode to TRUE/FALSE
public function getFatalErrMode ( ) {} -> BOOL
@return: {TRUE/FALSE}
Laminas/DB: Get Fatal Error TRUE/FALSE
public function getObjectId ( string $id ) {} -> MIXED
@return: {MIXED} return a MongoDB ObjectId as OBJECT or STRING if invalid Id
Get the MongoDB ObjectId by Id
public function getFtsDictionaryByLang ( string $lang ) {} -> STRING
@return: {STRING} dictionary name (ex: 'english' - if available or 'none' - if n/a)
Get the MongoDB FTS (Full Text Search) Dictionary by Two Letter language code (ISO 639-1)
public function escapeFtsText ( string $text ) {} -> STRING
@return: {STRING} FTS escaped
Escape FTS text, to be used in a safe mode with mongo Full Text Search
public function escapeRegexText ( string $text ) {} -> STRING
@return: {STRING} Regex escaped
Escape Regex text, to be used in a safe mode with mongo $regex => 'text...'
public function is_command_ok ( $result ) {} -> BOOLEAN
@return: {BOOLEAN} TRUE / FALSE
Test if a command output is OK compliant (will check if result[0][ok] == 1)
Notice: not all MongoDB commands will return this standard answer, but majority
public function __call ( ) {} @ 
@throws: {Exception} Depending how this class it is constructed it may throw Exception or Raise Fatal Error
This is the Magic Method (Call) that maps the PHP class extra methods to MongoDB methods.
It have variadic parameters mapped to MongoDB sub-calls.
Sample code: PHP
<?php // Sample Count Records $count = $mongo->count( 'myTestCollection', [ 'name' => [ '$eq' => 'Test:!' ] ] // filter ); var_dump($count); // Sample Find One $find = $mongo->findone( 'myTestCollection', [ 'cost' => 7 ] // filter ); var_dump($find); // Sample Find Many $mfind = $mongo->find( 'myTestCollection', [ 'name' => 'John' ], // filter [ // projection 'name', 'description' ], [ 'limit' => 10, // limit 'skip' => 0 // offset ] ); var_dump($mfind); // Sample Insert $doc = []; $doc['id'] = $mongo->assign_uuid(); $doc['name'] = 'My Name'; $doc['description'] = 'Some description goes here ...'; $insert = $mongo->insert('myTestCollection', (array)$doc); $doc = []; var_dump($insert); // Sample Bulk Insert (10 Documents) $docs = array(); for($i=0; $i<10; $i++) { $docs[] = [ 'id' => $mongo->assign_uuid(), 'name' => 'Document #'.$i, 'cost' => ($i+1), 'data' => [ 'description' => 'This is the document #'.$i, 'date_time' => (string) date('Y-m-d H:i:s'), 'rating' => Smart::random_number(1,9) / 100 ] ]; } //end for $insert = $mongo->bulkinsert('myTestCollection', (array)$docs); $docs = array(); var_dump($insert); // Sample Complete Update (Replace) ; it will completely replace the document with a new one, except the _id UID key, by _id ; works only with one document ; if more documents match the criteria, only the first one will be updated $doc = []; $doc['name'] = 'My New Name'; $doc['description'] = 'Some description goes here ...'; $update = $mongo->update( 'myTestCollection', [ '_id' => 'XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX' ], // filter (update only this) [ 0 => (array) $doc ] // replace array ); $doc = []; var_dump($update); // Sample Partial Update, will update one or many: name and description ; if other keys exist in the stored document they remain unchanged $doc = []; $doc['name'] = 'My New Name'; $doc['description'] = 'Some description goes here ...'; $update = $mongo->update( 'myTestCollection', [ 'id' => 'XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX' ], // filter (update only this) '$set', // increment operation (array) $doc // update array ); $doc = []; var_dump($update); // Sample Upsert $doc = []; $docID = 'XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXX'; // comes from $mongo->assign_uuid(); $doc['name'] = 'My Newest Name'; $doc['description'] = 'Some description goes here ...'; try { $upsert = $mongo->upsert( 'myTestCollection', [ 'id' => $docID ], // filter (update only this) [ // also the $mongo->update() can use this style of associative array '$setOnInsert' => (array) [ 'id' => $docID ], // just on insert '$set' => (array) $doc, // update array '$addToSet' => (array) [ 'updated' => date('Y-m-d H:i:s') ] // update array #2 using $addToSet (can be also: $push or $inc, ...) ] ); } catch(Exception $err) { // if upsert goes wrong ... } $doc = []; var_dump($upsert); // Sample Delete $delete = $mongo->delete( 'myTestCollection', [ 'name' => 'An Item', 'cost' => 8 ] // filter ); var_dump($delete); // Search Distinct with Filter $filter = $mongo->command( [ 'distinct' => 'myTestCollection', 'key' => 'cost', 'query' => [ 'cost' => [ '$gte' => 5 ] ] // find distinct where cost > 5 ] ); if(!$mongo->is_command_ok($filter) { // command failed ... } var_dump($filter); // ... see more usage samples: modules/mod-samples/libs/TestUnitMongoDB.php // #end php code

public function count ( STRING $strCollection, ARRAY $arrQuery ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrQuery
count documents in a collection
public function find ( STRING $strCollection, ARRAY $arrQuery, ARRAY $arrProjFields, ARRAY $arrOptions ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrQuery
@param {ARRAY} $arrProjFields
@param {ARRAY} $arrOptions
find single or multiple documents in a collection with optional filter criteria / limit
public function findone ( STRING $strCollection, ARRAY $arrQuery, ARRAY $arrProjFields, ARRAY $arrOptions ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrQuery
@param {ARRAY} $arrProjFields
@param {ARRAY} $arrOptions
find single document in a collection with optional filter criteria / limit
public function bulkinsert ( STRING $strCollection, ARRAY $arrMultiDocs ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrMultiDocs
add multiple documents to a collection
public function insert ( STRING $strCollection, ARRAY $arrDoc ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrDoc
add single document to a collection
public function upsert ( STRING $strCollection, ARRAY $arrFilter, MIXED $strUpdOpOrArrUpd, ARRAY $arrUpd ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrFilter
@param {MIXED} $strUpdOpOrArrUpd
@param {ARRAY} $arrUpd
insert single or modify single or multi documents in a collection that are matching the filter criteria
public function update ( STRING $strCollection, ARRAY $arrFilter, MIXED $strUpdOpOrArrUpd, ARRAY $arrUpd ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrFilter
@param {MIXED} $strUpdOpOrArrUpd
@param {ARRAY} $arrUpd
modify single or many documents in a collection that are matching the filter criteria
public function delete ( STRING $strCollection, ARRAY $arrFilter ) {} -> MIXED
@magic __call()
@return {MIXED}
@param {STRING} $strCollection
@param {ARRAY} $arrFilter
delete single or many documents from a collection that are matching the filter criteria
public function command ( $arrCmd ) {} -> MIXED
@magic __call()
@return {MIXED}
@param $arrCmd
run a command over database like: aggregate, distinct, mapReduce, create Collection, drop Collection, ...
public function igcommand ( $arrCmd ) {} -> MIXED
@magic __call()
@return {MIXED}
@param $arrCmd
run a command over database and ignore if error ; in the case of throw error will ignore it and will not stop execution ; will return the errors instead of result like: create Collection which may throw errors if collection already exists, drop Collection, similar if does not exists

class Properties


class Constants


Sample code: PHP

<?php

// sample mongo config
 
$cfg_mongo = array();
 
$cfg_mongo['type']         = 'mongo-standalone';                 // mongodb server(s) type: 'mongo-standalone' | 'mongo-cluster' (sharding) | 'mongo-replica-set:My-Replica' (replica set)
 
$cfg_mongo['server-host']    = '127.0.0.1';                            // mongodb host or comma separed list of multiple hosts
 
$cfg_mongo['server-port']    = '27017';                                    // mongodb port
 
$cfg_mongo['dbname']        = 'smart_framework';            // mongodb database
 
$cfg_mongo['username']         = '';                                            // mongodb username
 
$cfg_mongo['password']         = '';                                            // mongodb Base64-Encoded password
 
$cfg_mongo['timeout']        = 5;                                                // mongodb connect timeout in seconds
 
$cfg_mongo['slowtime']        = 0.0035;                                    // 0.0025 .. 0.0090 slow query time (for debugging)

 // sample mongo connect
 
$mongo = new SmartMongoDb($cfg_mongo);

// #end php code


documentation generated on: 2023-10-19 23:15:47 +0000


Smart.Framework © 2009-2023 unix-world.org