Skip to content
Dmitriy Verkhoumov edited this page Aug 29, 2017 · 20 revisions

CodeIgniter MongoDB Library

Requirements

  • PHP 7.1+, PECL extension
  • CodeIgniter 3+
  • MongoDB 3.2+

Install

In order to install library download latest release and merge folder application with the same folder in your project. There is only 2 files:

application/
├── config/
│   └── mongo_db.php
└── libraries/
    └── Mongo_db.php

Everything is in one file, so there's not need to work with multiple namespaces.

Use

// Include library
$this->load->library('mongo_db');

// Create new connection
$this->mongo_db->connect();

// Execute select query
$result = $this->mongo_db
               ->select(['_id', 'title', 'cost'])
               ->where_gt('cost', 200.25)
               ->getOne('payment');

// First row
$payment = $this->mongo_db->row_array($result);

NOTE: Although the getOne method is used to limit the result to one document, then the most single (and thus the first) document is extracted from the result obtained by the row_array method. First, it preserves the logic of the application - when you execute the query, you will receive a list of documents. Secondly, the getOne method allows you to restrict the result to native MongoDB.

MongoDB driver configuration

If necessary, you can change the values of the following MongoDB manager driver parameters:

  • WRITE_CONCERN_MODE — with help of WriteConcern namespace. Default is WriteConcern::MAJORITY.
  • WRITE_CONCERN_TIMEOUT — default is 1000.
  • WRITE_CONCERN_JOURNAL — default is FALSE.
  • BULK_WRITE_OPTIONS — default is ['ordered' => TRUE].
  • READ_PREFERENCE_MODE — with help of ReadPreference namespace. Default is ReadPreference::RP_PRIMARY.
  • READ_CONCERN_LEVEL — with help of ReadConcern namespace. Default is ReadConcern::LOCAL.

To change these parameters, change the value of the corresponding constants in the source code of the file /application/libraries/Mongo_db.php.

Other driver parameters (allow_invalid_hostname, ca_dir, ca_file, etc.) can be set using the configuration file (see driver settings in configuration file).