Can anyone assist in pointing me to a tutorial, library, etc. that will allow me to work with MongoDB from CodeIgniter?
-
check this out https://github.com/vesparny/cimongo-codeigniter-mongodb-library – Feb 26 '12 at 23:18
-
I have a doubt. Mongodb query syntax is already simple. There is no need to write complex SQL's. Why don't you disable "ActiveRecord" class in config and write your own queries using default mongo driver? – user10 Jul 04 '13 at 07:48
5 Answers
I'm not sure if its the "CodeIgniter way" but I created a CodeIgniter library that extends the Mongo class with an extra property to store the current database connection.
Here are the relevant code files from my project.
config/mongo.php
$config['mongo_server'] = null;
$config['mongo_dbname'] = 'mydb';
libraries/Mongo.php
class CI_Mongo extends Mongo
{
var $db;
function CI_Mongo()
{
// Fetch CodeIgniter instance
$ci = get_instance();
// Load Mongo configuration file
$ci->load->config('mongo');
// Fetch Mongo server and database configuration
$server = $ci->config->item('mongo_server');
$dbname = $ci->config->item('mongo_dbname');
// Initialise Mongo
if ($server)
{
parent::__construct($server);
}
else
{
parent::__construct();
}
$this->db = $this->$dbname;
}
}
And a sample controller
controllers/posts.php
class Posts extends Controller
{
function Posts()
{
parent::Controller();
}
function index()
{
$posts = $this->mongo->db->posts->find();
foreach ($posts as $id => $post)
{
var_dump($id);
var_dump($post);
}
}
function create()
{
$post = array('title' => 'Test post');
$this->mongo->db->posts->insert($post);
var_dump($post);
}
}

- 7,433
- 2
- 31
- 22
-
Stephen What about models? Is there any special consideration that has to be given there? – IEnumerator Feb 21 '10 at 06:05
-
I was able to get the models functionality working also. Nothing special, still inherit from Model and your functions just have to call Mongo specific functions. Easy – IEnumerator Feb 21 '10 at 22:28
-
Exactly. You should be able to go $this->mongo->db directly in your model code. – Stephen Curran Feb 25 '10 at 09:13
-
This is great stuff are there any plans to release more documentation or to expand on how to search and retrieve documents? – whobutsb Mar 03 '10 at 16:39
-
Its the Mongo DB PHP driver. So you'd use the library as you would normally outside of CodeIgniter. Have you seen the Mongo DB PHP driver doc? http://www.php.net/manual/en/book.mongo.php – Stephen Curran Mar 03 '10 at 18:52
-
-
Thanks for this Stephen, i was just curious, do you know what `parent::__construct($server);` does ? – aziz punjani Sep 22 '11 at 15:21
-
It invokes the parent constructor, in this case the constructor of the Mongo class (http://php.net/manual/en/class.mongo.php), passing in the host name/ip address of where the Mongo DB server is running. – Stephen Curran Sep 24 '11 at 10:30
-
8$ci =& get_instance() should be used instead. From CI docs: This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it. – Vitaly Dec 19 '11 at 10:41
-
@StephenCurran I have a doubt. Mongodb query syntax is already simple. There is no need to write complex SQL's. Why don't you disable "ActiveRecord" class in config and write your own queries using default mongo driver? – user10 Jul 04 '13 at 07:48
-
Hi, my settings were already made for mysql, and now I am trying to change them for mongodb. I also have libraries\Mysmarty.php and in config\database a have set $db['default']['database'] = 'application'; $db['default']['dbdriver'] = 'mysql';.........What should I do with these ones? If a just delete "mysql" and relace it with "mongo" it does not work – Lulu Feb 06 '16 at 15:33
MongoDB is very well supported within CodeIgniter community, take the time and dive in :p
- CodeIgniter MongoDB Active Document Library [BROKEN LINK]
- CodeIgniter MongoDB Session Library [OBSOLETE]
- CodeIgniter MongoDB Authentication Library [OBSOLETE]
- CodeIgniter MongoDB REST Server Library [OBSOLETE]
- CodeIgniter MongoDB Base Model [OBSOLETE]
-
2Thank you. Two years ago there wasn't much but I agree that support for Mongo is much better now. – IEnumerator Aug 14 '12 at 17:45
-
https://amit-tips-for-techie.blogspot.com/2023/04/connect-codeigniter-with-mongodb.html – Amit Jha Apr 18 '23 at 00:18
I like Stephen Curran's example as it is simple and allows an interface to Mongo without too much functionality written within Php, I tend to find huge abstraction clases a bit much at times for what I am after.
I have extended his example to include database authentication. Go here: http://www.mongodb.org/display/DOCS/Security+and+Authentication to read about mongo authentication, don't forget to enable authentication for the Mongo Server you are connecting to.
I have also changed the old style constructor function to be __construct and am handling Mongo Connection Exceptions as they can reveal your username and password.
config/mongo.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['mongo_server'] = 'localhost';
$config['mongo_dbname'] = 'my_mongo_db';
$config['mongo_username'] = 'mongo_user';
$config['mongo_password'] = 'password1234';
/* End of file mongo.php */
libraries/Mongo.php
<?php
class CI_Mongo extends Mongo{
protected $db;
function __construct()
{
// Fetch CodeIgniter instance
$ci = get_instance();
// Load Mongo configuration file
$ci->load->config('mongo');
// Fetch Mongo server and database configuration
$server = $ci->config->item('mongo_server');
$username = $ci->config->item('mongo_username');
$password = $ci->config->item('mongo_password');
$dbname = $ci->config->item('mongo_dbname');
// Initialise Mongo - Authentication required
try{
parent::__construct("mongodb://$username:$password@$server/$dbname");
$this->db = $this->$dbname;
}catch(MongoConnectionException $e){
//Don't show Mongo Exceptions as they can contain authentication info
$_error =& load_class('Exceptions', 'core');
exit($_error->show_error('MongoDB Connection Error', 'A MongoDB error occured while trying to connect to the database!', 'error_db'));
}catch(Exception $e){
$_error =& load_class('Exceptions', 'core');
exit($_error->show_error('MongoDB Error',$e->getMessage(), 'error_db'));
}
}
}

- 5,380
- 2
- 29
- 36

- 111
- 1
- 3
-
-
Possibly, however if a user wants to run against a mongo server without the --auth flag then they could just use the original post by Stephen Curran. Or adapt mine as necessary. Luke – Luke Tarplin Nov 22 '11 at 10:38
Working with MongoDB in CodeIgniter wouldn't be much different than working with it anywhere else.
You could knock together a MongoDB library that would connect in the constructor and store $this->conn to be used in methods later on.
then either work directly with the conn property in your controllers or create a few methods in your MongoDB library to do this for you.
Take a look here to see the plain PHP tutorial for working with MongoDB.
I'd happily create you a library for this but it would come with a price. :-p

- 30,637
- 12
- 78
- 117
-
thank you - i realize that with the MongoDB Driver and the above PHP tutorial i can make it all happen. – IEnumerator Feb 13 '10 at 21:55
-
3If you create a good library please share it with the community. Id love an excuse to play with MongoDB. :-) – Phil Sturgeon Feb 14 '10 at 15:40
-
-
Sweet, I only wish I had the time to make one myself. :-) Looks cool. – Phil Sturgeon Feb 16 '10 at 09:11
-
-
@Piers just shared a library in the answer below: http://stackoverflow.com/questions/2248789/mongodb-and-codeigniter/4865588#4865588 – IEnumerator Feb 02 '11 at 11:45
I'm using MongoDB w/ CI and came up with the following. It works for me, but I'm sure it can be tweaked somewhat. I'll worry about tweaking it later but right now it does what I want.
I created a model called "database_conn.php"
class Database_Conn extends Model {
function _connect() {
$m = new Mongo();
$db = $m->selectDB( "YOUR DATABASE NAME" );
return $db;
}
}
Then, if I need to connect to a collection from my models.
$collection = Database_Conn::_connect()->selectCollection( "COLLECTION NAME" );

- 10,046
- 26
- 88
- 122