CodeIgniter 4 MongoDB Tutorial
    About Lesson

    In this tutorial, we will implement the steps to integrate MongoDB with CodeIgniter 4 and perform basic CRUD operations.

     

    Step 1: Set Up CodeIgniter 4

    If you haven’t already set up CodeIgniter 4, you can create a new project with Composer:

    composer create-project codeigniter4/ci4mongodb

    OR

    Create ci4mongodb in your XAMPP’s htdocs folder and navigate to the project directory:

     


     

    Step 2: Install MongoDB PHP Driver

    To connect MongoDB with CodeIgniter, you need to install the MongoDB PHP driver. Run the following command using Composer:

    composer require mongodb/mongodb

     


     

    Step 3: Configure MongoDB Connection

    Create a library class to manage the MongoDB connection. In CodeIgniter 4, database connections are typically defined in the configuration files, but for MongoDB, we will create a custom connection file.

    Create a new file: app/Library/MongoDbConnection.php

    namespace App/Libraries;

    use MongoDB/Client;

    class MongoDbConnection {

    protected $client;
    protected $db;

    public function __construct() {
    // Connect to MongoDB
    $this->client = new Client("mongodb://localhost:27017");

    // Select the database
    $this->db = $this->client->selectDatabase('ci4mongo_db');
    }

    public function getCollection($collection) {
    return $this->db->selectCollection($collection);
    }

    }

    This class will manage the connection to MongoDB. It uses the MongoDBClient class provided by the MongoDB PHP driver.

    Note: Please replace the (/) with a backward slash for the following code.

    namespace App/Libraries;
    use MongoDB/Client;

     


     

    Step 4: Create a Model for CRUD Operations

    Now that we have the MongoDB connection, let’s create a model to handle CRUD operations.

    Create a file app/Models/login/LoginModel.php:

    namespace App/Models/login;
    use App/Libraries/MongoDbConnection;

    class LoginModel {

    protected $collection;

    public function __construct() {
    $mongoDB = new MongoDbConnection();
    $this->collection = $mongoDB->getCollection('login_info');
    }

    // Create a new user
    public function createEntry($data) {
    $result = $this->collection->insertOne($data);
    return $result->getInsertedId();
    }

    // Get all users
    public function getEntryList($filter = [], $options = []) {
    return $this->collection->find($filter, $options)->toArray();
    }

    // Get a user by ID
    public function getEntry($filter = [], $options = []) {
    // return $this->collection->findOne(['_id' => new MongoDBBSONObjectId($id)]);
    return $this->collection->findOne($filter, $options);
    }

    // Update a user by ID
    public function updateEntry($filter, $newData) {
    // return $this->collection->updateOne(
    // ['_id' => new MongoDBBSONObjectId($id)],
    // ['$set' => $data]
    // );
    return $this->collection->updateOne($filter, ['$set' => $newData]);
    }

    // Delete a user by ID
    public function deleteEntry($filter) {
    // return $this->collection->deleteOne(['_id' => new MongoDBBSONObjectId($id)]);
    return $this->collection->deleteOne($filter);
    }
    }

    This model allows you to perform basic CRUD operations: Create, Read, Update, and Delete. It connects to MongoDB through the MongoDbConnection class and performs operations on the specified collection.

    Note: Please replace the (/) with a backward slash for the following code.

    namespace App/Models/login;
    use App/Libraries/MongoDbConnection;

     


     

    Create a file app/Models/login/LoginDeferModel.php:

    namespace App/Models/login;
    use App/Libraries/MongoDbConnection;

    class LoginDeferModel {

    protected $collection;

    public function __construct() {
    $mongoDB = new MongoDbConnection();
    $this->collection = $mongoDB->getCollection('login_info');
    }

    public function getRows($searchValue, $start, $length) {
    $filter = [];
    if ($searchValue) {
    // $filter = ['name' => ['$regex' => $searchValue, '$options' => 'i']];
    $filter = ['$or' => [
    ['name' => ['$regex' => $searchValue, '$options' => 'i']],
    ['email' => ['$regex' => $searchValue, '$options' => 'i']],
    ['mobile_number' => ['$regex' => $searchValue, '$options' => 'i']],
    ]];
    }

    $options = [
    'skip' => $start,
    'limit' => $length,
    ];

    $rows = $this->collection->find($filter, $options)->toArray();
    $totalRecords = $this->collection->countDocuments();
    $filteredRecords = $this->collection->countDocuments($filter);

    return [
    'data' => $rows,
    'recordsTotal' => $totalRecords,
    'recordsFiltered' => $filteredRecords,
    ];
    }
    }

     

    Note: Please replace the (/) with a backward slash for the following code.

    namespace App/Models/login;
    use App/Libraries/MongoDbConnection;

     


     

    Step 5: Create a Controller for CRUD Operations

    Now let’s create a controller to handle the requests.

    Create a new file app/Controllers/login/Login.php:

    namespace App/Controllers/login;
    use App/Controllers/BaseController;
    use App/Models/login/LoginModel;
    use App/Models/login/LoginDeferModel;

    class Login extends BaseController {

    protected $login;

    public function __construct() {

    $this->login = new LoginModel();
    $this->loginDefer = new LoginDeferModel();

    $this->ip_address = $_SERVER['REMOTE_ADDR'];
    $this->datetime = date("Y-m-d H:i:s");
    }

    public function index() {
    $this->list();
    }

    public function list() {
    $data = [];
    $data['content_title'] = 'List | CodeIgniter 4 MongoDB';
    $data['main_content'] = 'login/list';
    echo view("innerpages/template", $data);
    }

    public function add() {
    $data = [];
    $data['content_title'] = 'Add | CodeIgniter 4 MongoDB';
    $data['main_content'] = 'login/add';
    echo view("innerpages/template", $data);
    }

    public function edit() {
    $id = $this->request->getGet('id');
    $where = [
    '_id' => new MongoDBBSONObjectId($id),
    ];
    $result = $this->login->getEntry($where);
    if($result) {
    $data = [];
    $data['content_title'] = 'Update | CodeIgniter 4 MongoDB';
    $data['main_content'] = 'login/edit';
    $data['result'] = $result;
    echo view("innerpages/template", $data);
    } else {
    return redirect()->to(base_url());
    }
    }

    public function create() {
    $name = $this->request->getPost('name');
    $email = $this->request->getPost('email');
    $mobile_number = $this->request->getPost('mobile_number');
    $password = $this->request->getPost('password');

    $where = [
    'email' => $email,
    ];
    $result = $this->login->getEntry($where);
    if($result) {
    $json = [
    'message' => "<span class='text-danger'>Entered email address is already exists.</span>",
    'status' => false,
    ];
    } else {
    $data = [
    'name' => $name,
    'email' => $email,
    'mobile_number' => $mobile_number,
    'password' => md5($password),
    'created_at' => $this->datetime,
    'ip_address' => $this->ip_address,
    'status' => "1",
    ];
    $login_id = (string) $this->login->createEntry($data);
    if($login_id) {
    $json = [
    'message' => "<span class='text-success'>New login has been created successfully.</span>",
    'location' => base_url(),
    'status' => true,
    ];
    } else {
    $json = [
    'message' => "<span class='text-danger'>Something went wrong. Please try again.</span>",
    'status' => false,
    ];
    }
    }
    echo json_encode($json);
    }

    public function update() {
    $id = $this->request->getPost('id');
    $name = $this->request->getPost('name');
    $email = $this->request->getPost('email');
    $mobile_number = $this->request->getPost('mobile_number');
    $password = $this->request->getPost('password');

    $where = [
    'email' => $email,
    ];
    $result = $this->login->getEntry($where);
    $dbId = ($result) ? (string) $result->_id : '';
    if($dbId != $id) {
    $json = [
    'message' => "<span class='text-danger'>Entered email address is already exists.</span>",
    'status' => false,
    ];
    } else {
    $data = [
    'name' => $name,
    'email' => $email,
    'mobile_number' => $mobile_number,
    'password' => md5($password),
    'created_at' => $this->datetime,
    'ip_address' => $this->ip_address,
    'status' => "1",
    ];
    $where = [
    '_id' => new MongoDBBSONObjectId($id),
    ];
    $result = $this->login->updateEntry($where, $data);
    if($result) {
    $json = [
    'message' => "<span class='text-success'>Selected login has been updated successfully.</span>",
    'location' => base_url(),
    'status' => true,
    ];
    } else {
    $json = [
    'message' => "<span class='text-danger'>Something went wrong. Please try again.</span>",
    'status' => false,
    ];
    }
    }
    echo json_encode($json);
    }

    public function delete() {
    $id = $this->request->getPost('id');
    $where = [
    '_id' => new MongoDBBSONObjectId($id),
    ];
    $result = $this->login->deleteEntry($where);
    if($result) {
    $json = [
    'message' => "<span class='text-success'>Selected login has been deleted successfully.</span>",
    'status' => true,
    ];
    } else {
    $json = [
    'message' => "<span class='text-danger'>Something went wrong. Please try again.</span>",
    'status' => false,
    ];
    }
    echo json_encode($json);
    }

    public function datatable() {
    $draw = $this->request->getPost('draw');
    $start = $this->request->getPost('start');
    $length = $this->request->getPost('length');
    $searchValue = $this->request->getPost('search')['value'];
    $result = $this->loginDefer->getRows($searchValue, (int) $start, (int) $length);
    $arrayList = $this->getRows($start, $result['data']);
    $response = [
    'draw' => (int) $draw,
    'recordsTotal' => $result['recordsTotal'],
    'recordsFiltered' => $result['recordsFiltered'],
    'data' => $arrayList,
    ];
    echo json_encode($response);
    }

    function getRows($start, $result) {
    $arrayList = [];
    foreach ($result as $row) {
    $action = '
    <a href="'.base_url('edit?id=' . (string) $row->_id).'" class="btn btn-primary">Edit</a>
    <button type="button" name="btn-delete" data-id="'.(string) $row->_id.'" class="btn btn-danger">Delete</button>
    ';
    $arrayList [] = [
    ++$start,
    $row->name,
    $row->email,
    $row->mobile_number,
    $action,
    ];
    }
    return $arrayList;
    }

    }

     

    Note: Please replace the (/) with a backward slash for the following code.

    namespace App/Controllers/login;
    use App/Controllers/BaseController;
    use App/Models/login/LoginModel;

     

    Step 6: Define Routes

    You need to define routes to access the CRUD operations. Open app/Config/Routes.php and add the following:

    $routes->get('/', 'login/Login::index');

    $routes->get('add', 'login/Login::add');
    $routes->get('edit', 'login/Login::edit');
    $routes->post('create', 'login/Login::create');
    $routes->post('update', 'login/Login::update');
    $routes->post('delete', 'login/Login::delete');
    $routes->post('datatable', 'login/Login::datatable');

     

    Note: Please replace the (/) with a backward slash for the following code.

     


     

    Step 7: Create views header.php, footer.php, and template.php for reusable structure.

    Create a new file app/View/innperpages/header.php:

    <!DOCTYPE html>
    <html lang="en">

    <head>
    <title><?php echo $content_title; ?></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/2.1.7/css/dataTables.dataTables.min.css">
    <link href="https://cdn.datatables.net/buttons/3.1.2/css/buttons.dataTables.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/2.1.7/js/dataTables.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/3.1.2/js/dataTables.buttons.min.js"></script>

    </head>

    <body>
    <div class="container-fluid p-5 bg-primary text-white text-center">
    <h1><?php echo $content_title; ?></h1>
    </div>

    <div class="container mt-5">
    <div class="row">
    <div class="col-sm-3"></div>
    <div class="col-sm-6">
    <div class="result"></div>
    </div>
    </div>
    </div>

     

     

    Create a new file app/View/innperpages/footer.php:


    </body>
    </html>

     

    Create a new file app/View/innperpages/template.php:

    <?php 
    echo view('innerpages/header');
    echo view($main_content);
    echo view('innerpages/footer');

     


     

    Step 7: Create views to display CRUD Interface

    Create a new file app/View/login/list.php:

    List CodeIgniter 4 MongoDB CRUD

     

    <div class="container mt-5">
    <div class="row">
    <div class="col-sm-2"></div>

    <div class="col-sm-8">
    <a href="<?php echo base_url('add') ?>" class="btn btn-primary">+ Add User</a>

    <div class="table-responsive mt-5">
    <table id="table-login" width="100%" class="table table-striped">
    <thead>
    <tr>
    <th>No.</th>
    <th>Name</th>
    <th>Email</th>
    <th>Mobile No.</th>
    <th>#</th>
    </tr>
    </thead>
    </table>
    </div>
    </div>

    </div>
    </div>

    <?php
    echo view('login/scripts');
    ?>

     

    Create a new file app/View/login/add.php:

    Add CodeIgniter 4 MongoDB CRUD

    <div class="container mt-5">
    <div class="row">
    <div class="col-sm-3"></div>

    <div class="col-sm-6">
    <a href="<?php echo base_url() ?>" class="btn btn-danger">Back</a>

    <form method="post" id="form-add-login" autocomplete="off" class="mt-3">
    <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" placeholder="Name" class="form-control" required>
    </div>
    <div class="form-group mt-3">
    <label>Email</label>
    <input type="email" name="email" placeholder="Email" class="form-control" required>
    </div>
    <div class="form-group mt-3">
    <label>Mobile No.</label>
    <input type="text" name="mobile_number" placeholder="Mobile No." class="form-control" maxlength="10" minlength="10" required>
    </div>
    <div class="form-group mt-3">
    <label>Password</label>
    <input type="password" name="password" placeholder="Password" class="form-control" required>
    </div>
    <div class="form-group mt-3">
    <button type="submit" class="btn btn-primary">Add User</button>
    </div>
    </form>

    </div>
    </div>
    </div>

    <?php
    echo view('login/scripts');
    >

     

    Create a new file app/View/login/edit.php:

    Update CodeIgniter 4 MongoDB CRUD

    <div class="container mt-5">
    <div class="row">
    <div class="col-sm-3"></div>

    <div class="col-sm-6">
    <a href="<?php echo base_url() ?>" class="btn btn-danger">Back</a>

    <form method="post" id="form-update-login" autocomplete="off" class="mt-3">
    <input type="hidden" name="id" value="<?php echo (string) $result->_id; ?>">
    <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" placeholder="Name" class="form-control" value="<?php echo $result->name; ?>" required>
    </div>
    <div class="form-group mt-3">
    <label>Email</label>
    <input type="email" name="email" placeholder="Email" class="form-control" value="<?php echo $result->email; ?>" required>
    </div>
    <div class="form-group mt-3">
    <label>Mobile No.</label>
    <input type="text" name="mobile_number" placeholder="Mobile No." class="form-control" maxlength="10" minlength="10" value="<?php echo $result->mobile_number; ?>" required>
    </div>
    <div class="form-group mt-3">
    <label>Password</label>
    <input type="password" name="password" placeholder="Password" class="form-control">
    </div>
    <div class="form-group mt-3">
    <button type="submit" class="btn btn-primary">Update User</button>
    </div>
    </form>

    </div>
    </div>
    </div>

    <?php
    echo view('login/scripts');
    >

     

    Create a new file app/View/login/scripts.php:

    <script type="text/javascript">
    $(document).ready(function() {
    $("body").on("submit", "#form-add-login", function(e) {
    e.preventDefault();
    let data = $(this).serialize();
    $.post('<?php echo base_url("create") ?>', data, function(result) {
    if(result.status) {
    $(".result").html(result.message);
    let link_open = window.open(result.location, "_self");
    link_open.focus();
    } else {
    $(".result").html(result.message);
    }
    }, 'json');
    });

    $("body").on("submit", "#form-update-login", function(e) {
    e.preventDefault();
    let data = $(this).serialize();
    $.post('<?php echo base_url("update") ?>', data, function(result) {
    if(result.status) {
    $(".result").html(result.message);
    let link_open = window.open(result.location, "_self");
    link_open.focus();
    } else {
    $(".result").html(result.message);
    }
    }, 'json');
    });

    var table_login = $('#table-login').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
    "url" : "<?= base_url('datatable') ?>",
    "type" : "POST",
    },
    });

    $("#table-login tbody").on('click', 'button', function() {
    var id = $(this).attr('data-id');
    if(this.name == "btn-delete") {
    var is_delete = confirm("Are your sure?");
    if(is_delete) {
    $.post('<?php echo base_url("delete") ?>', {id: id}, function(result) {
    if(result.status) {
    $(".result").html(result.message);
    table_login.ajax.reload();
    } else {
    $(".result").html(result.message);
    }
    }, 'json');
    }
    }
    });
    });
    </script>

     


     

    Step 8: Testing CRUD Operations

    With everything set up, you can test your CRUD operations using Postman or any other API client.

    • Create (POST): http://localhost:8081/create with JSON data
    • Read (GET): http://localhost:8080/edit?id=
    • Update (POST): http://localhost:8080/update with JSON data
    • Delete (POST): http://localhost:8080/delete

     

    In this tutorial, we learned how to integrate MongoDB with CodeIgniter 4 and perform basic CRUD operations. This is just the beginning, and you can further extend this setup to handle more advanced MongoDB functionalities.

    Get the source code for free: Click Here