How to use $inc in FuelPHP with mongoDB
So if you want to use $inc with fuelphp and mongodb, or any of the other update commands besides $set ( which is the default) it is possible. It's undocumented however unless you look into the code. Again here is our controller code
Class Controller_About extends Controller { public function action_index() { $data = array(); $data['name'] = "CopyPasteCoder"; $data['age'] = 27; //echo "This is my first attempts at MVC architecture."; return View::forge('about', $data); } public function action_water() { $result = Model\About::get_count(); echo "i'm thirsty $result"; } public function action_supMe($name = '') { $data = array(); $data['name'] = $name; $data['age'] = 27; return View::forge('about', $data); } }
And our model looks like this
namespace Model; class About extends \Model { public static function get_count() { $mongodb = \Mongo_Db::instance('default'); $result = $mongodb->where(array("name"=>'about'))->get('counter'); $count = $result[0]['count']; return $count; } }
let's modify the get_count() function to actually increment the count in 2 ways.
public static function get_count() { $mongodb = \Mongo_Db::instance('default'); //increment the old fashion way, get row then increment $result = $mongodb->get('counter'); $count = $result[0]['count'] + 1; $mongodb->where(array('name'=> 'about'))->update('counter', array('count'=> $count) ) ; //using increment functionality ($inc) $mongodb->where(array('name'=>'about'))->update('counter', array('$inc' => array('count'=>1)), array(), true); return $count; }
the first way is the classic way of incrementing. Get counter, increment, update with set. The second way is calling update with an extra hidden field. So the function definition for update is public function update($collection = '', $data = array(), $options = array(), $literal = false) What we want to do in JSON is db.counter.update({"name":"about"}, {$inc : {"count" : 1}}) So lets break it down where(array('name'=>'about')) = {"name":"about"} array('$inc' => array('count'=>1)) = {$inc : {"count" : 1}} Then i pass in a blank array(), because i don't have any options Then i pass in a true so $literal = true. THIS is what allows us to use $inc, otherwise it defaults to $set.














