Databases 7 min read

Introduction to MongoDB and a PHP Class for MongoDB Operations

This article introduces MongoDB as a popular NoSQL database, explains its schema‑free, collection‑oriented design, storage format, and platform support, and provides a complete PHP class that implements common CRUD and aggregation operations for MongoDB.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Introduction to MongoDB and a PHP Class for MongoDB Operations

MongoDB is a representative NoSQL database that has become very popular in recent years due to its high performance, easy deployment, and flexible JSON‑like BSON storage format, offering powerful query capabilities similar to relational databases.

Data in MongoDB is organized into collections, which are analogous to tables but do not require a predefined schema, allowing documents with different structures to coexist in the same database.

Each document is stored as a key‑value pair, with keys as strings and values supporting complex data types; this format is called BSON (Binary Serialized Document Format).

The MongoDB server can run on Linux, Windows, or macOS, supports both 32‑bit and 64‑bit architectures (with a recommended 64‑bit deployment), and stores data in files under the default path /data/db using memory‑mapped files for efficiency.

The following PHP class provides a reusable wrapper for common MongoDB operations, including connection handling, CRUD methods, aggregation, and distinct queries.

<?php
/**
 * PHP operation class for MongoDB
 */
class Database {
    protected $database = '';
    protected $mo;

    /** Constructor */
    public function __construct() {
        $server   = DBSERVER;
        $user     = DBUSER;
        $password = DBPASS;
        $port     = DBPORT;
        $database = DBNAME;
        $mongo = $this->getInstance($server, $user, $password, $port);
        $this->database = $mongo->$database;
    }

    /** Singleton instance */
    public function getInstance($server, $user, $password, $port) {
        if (isset($this->mo)) {
            return $this->mo;
        } else {
            if (!empty($server)) {
                if (!empty($port)) {
                    if (!empty($user) && !empty($password)) {
                        $this->mo = new Mongo("mongodb://{$user}:{$password}@{$server}:{$port}");
                    } else {
                        $this->mo = new Mongo("mongodb://{$server}:{$port}");
                    }
                } else {
                    $this->mo = new Mongo("mongodb://{$server}");
                }
            } else {
                $this->mo = new Mongo();
            }
            return $this->mo;
        }
    }

    /** Get all records */
    public function getAll($table, $where = array(), $sort = array(), $limit = '', $skip = '') {
        $data = !empty($where) ? $this->database->$table->find($where) : $this->database->$table->find();
        if (!empty($sort))  $data = $data->sort($sort);
        if (!empty($limit)) $data = $data->limit($limit);
        if (!empty($skip))  $data = $data->skip($skip);
        $newData = array();
        while ($data->hasNext()) {
            $newData[] = $data->getNext();
        }
        return count($newData) == 0 ? 0 : $newData;
    }

    /** Get one record */
    public function getOne($table, $where = array()) {
        return !empty($where) ? $this->database->$table->findOne($where) : $this->database->$table->findOne();
    }

    /** Count records */
    public function getCount($table, $where = array()) {
        return !empty($where) ? $this->database->$table->find($where)->count() : $this->database->$table->find()->count();
    }

    /** Execute raw command */
    public function toExcute($sql) {
        return $this->database->execute($sql);
    }

    /** Group count aggregation */
    public function groupCount($table, $where, $field) {
        $cond = array(
            array('$match' => $where),
            array('$group' => array('_id' => '$' . $field, 'count' => array('$sum' => 1))),
            array('$sort' => array('count' => -1))
        );
        $this->database->$table->aggregate($cond);
    }

    /** Delete records */
    public function toDelete($table, $where) {
        $re = $this->database->$table->remove($where);
        return $re;
    }

    /** Insert record */
    public function toInsert($table, $data) {
        $re = $this->database->$table->insert($data);
        return $re;
    }

    /** Update records */
    public function toUpdate($table, $where, $data) {
        $re = $this->database->$table->update($where, array('$set' => $data));
        return $re;
    }

    /** Distinct values */
    public function distinctData($table, $key, $query = array()) {
        $where = !empty($query) ? array('distinct' => $table, 'key' => $key, 'query' => $query) : array('distinct' => $table, 'key' => $key);
        $data = $this->database->command($where);
        return $data['values'];
    }
}
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databasePHPCRUDMongoDBNoSQL
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.