How to connect with the mongodb through codeigniter?

Member

by daisha , in category: PHP Frameworks , 6 months ago

How to connect with the mongodb through codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 6 months ago

@daisha 

To connect with MongoDB through CodeIgniter, you can use the MongoDB PHP driver along with CodeIgniter's database class. Here are the steps to connect with MongoDB through CodeIgniter:

  1. First, you need to install the MongoDB PHP driver. You can do this by using composer. Run the following command in your terminal:
1
composer require mongodb/mongodb


  1. Next, you need to configure the MongoDB connection in CodeIgniter's database configuration file. Open the database.php file located in the application/config/ folder and add the following configuration for MongoDB:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
$db['mongo'] = array(
    'dsn' => '',
    'hostname' => 'mongodb://localhost:27017',
    'username' => '',
    'password' => '',
    'database' => 'your_database_name',
    'dbdriver' => 'mongo',
    'db_debug' => true,
    'cache_on' => false,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'compress' => false,
    'encrypt' => false,
    'stricton' => false,
    'failover' => array(),
    'save_queries' => true
);


  1. Now, you can load the MongoDB database connection in your CodeIgniter controller or model by using the following code:
1
$this->load->database('mongo');


  1. You can now use CodeIgniter's database functions to interact with the MongoDB database. Here is an example of how you could query the database:
1
2
3
4
$result = $this->mongo_db->get('collection_name');
foreach ($result as $row) {
    echo $row['name'];
}


That's it! You have successfully connected with MongoDB through CodeIgniter. You can now perform CRUD operations on your MongoDB database using CodeIgniter.