Mongodb and Codeigniter

MongoDB and CodeIgniter

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);
}
}

How can i select particular field using mongoDB with codeigniter?

Try following and let me know whether it is working or not

$collection->aggregate(
array(
'$match' => array(
'$and' => array(
array('email' => 'athira@gmail.com')
)
)
),
array(
'$group' => array(
'_id' => '$country'
)
)
);

Mongodb and Codeigniter Record between two dates

Date is in strtotime() .
I have changed it in the same format that is stored in database

$startDate=date('Y-m-d',$startDate);
$endDate=date('Y-m-d',$endDate);

$this->mongo_db->select("*");
$searchCriteria =array('created_date' => array('$gte' => $startDate, '$lte' => $endDate),'id' => $id);
$this->mongo_db->where($searchCriteria);
$results = $this->mongo_db->get('tbl_test');

The above code is tested i have done all type of testing. I have changed format of date only.



Related Topics



Leave a reply



Submit