Sunday, 2 October 2016

How to use mongodb in yii2 application

MongoDB is a document based database designed for scalability and agility. It stores the data in json like document instead of storing in tables and rows in relational databases like mysql.It is open source database and following are its features.

Yii2 MongoDb

MongoDB is schema less database which makes it flexible.
Dynamic schemas.
Geospatial support.
Its provides high performance.
Text search integrated.
Easy scalability.

In this post i will show you how mongodb is used in your yii2 application. In this post i'm expecting you have already installed the mongodb in your system if you not installed it then read here.

Step 1: you need to install the package library of mongodb before using it.

php composer.phar require --prefer-dist yiisoft/yii2-mongodb

or add it in your composer.json file.

"yiisoft/yii2-mongodb": "~2.1.0"

Step 2: After successfully installing the package you need to configure it in your config file.

return [
    'components' => [
        'mongodb' => [
            'class' => '\yii\mongodb\Connection',
            'dsn' => 'mongodb://developer:password@localhost:27017/yourdatabase',

Step 3: After putting the connection you can directly use it by using connection instance you may access databases and collections.

$collection = Yii::$app->mongodb->getCollection('employee');
$collection->insert(['name' => 'Mac', 'status' => 1]);

In this above command employee is your kind of table called collection in mongodb and it contains a document of name Mac in it.

Or you can also use it with model (ActiveRecord class).

use yii\mongodb\ActiveRecord;

class Employee extends ActiveRecord
     * @return string the name of the index associated with this ActiveRecord class.
    public static function collectionName()
        return 'employee';

     * @return array list of attribute names.
    public function attributes()
        return ['_id', 'name', 'email', 'address', 'status'];

In your controller you can call it like below:

Adding the namespace class in controller class.

use yii\data\ActiveDataProvider;
use yii\mongodb\Query;

For query you can use it like:

$query = new Query();
$query->from('employee')->where(['status' => 2]);
$provider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
$models = $provider->getModels();

I hope this post is helpful for you and if you find any problem related to configuration please comment below.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts