Skip to content

Instantly share code, notes, and snippets.

@jdu
Created July 30, 2012 22:39
Show Gist options
  • Save jdu/3211251 to your computer and use it in GitHub Desktop.
Save jdu/3211251 to your computer and use it in GitHub Desktop.
Returning a JSON result from MongoDB (CodeIgniter)
// connect
$m = new Mongo();
// select a database
$db = $m->shugah;
// select a collection (analogous to a relational database's table)
$collection = $db->entry_types;
// find everything in the collection
$cursor = $collection->find();
$return = array();
$i=0;
while( $cursor->hasNext() ) {
$return[$i] = $cursor->getNext();
// key() function returns the records '_id'
$return[$i++]['_id'] = $cursor->key();
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($return));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment