public
Last active — forked from lhitchon/gist:1424751

MongoHQ PHP Connection

  • Download Gist
mongohq.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
<!-- PHP Mongo Docs: http://php.net/manual/en/class.mongodb.php -->
<html>
<body>
<h1>MongoHQ Test</h1>
<?php
try {
// connect to MongoHQ assuming your MONGOHQ_URL environment
// variable contains the connection string
$connection_url = $_ENV["MONGOHQ_URL"]);
 
// create the mongo connection object
$m = new Mongo($connection_url);
 
// extract the DB name from the connection path
$url = parse_url($connection_url);
$db_name = preg_replace('/\/(.*)/', '$1', $url['path']);
 
// use the database we connected to
$db = $m->selectDB($db_name);
 
echo "<h2>Collections</h2>";
echo "<ul>";
 
// print out list of collections
$cursor = $db->listCollections();
$collection_name = "";
foreach( $cursor as $doc ) {
echo "<li>" . $doc->getName() . "</li>";
$collection_name = $doc->getName();
}
echo "</ul>";
 
// print out last collection
if ( $collection_name != "" ) {
$collection = $db->selectCollection($collection_name);
echo "<h2>Documents in ${collection_name}</h2>";
 
// only print out the first 5 docs
$cursor = $collection->find();
$cursor->limit(5);
echo $cursor->count() . ' document(s) found. <br/>';
foreach( $cursor as $doc ) {
echo "<pre>";
var_dump($doc);
echo "</pre>";
}
}
 
// disconnect from server
$m->close();
} catch ( MongoConnectionException $e ) {
die('Error connecting to MongoDB server');
} catch ( MongoException $e ) {
die('Mongo Error: ' . $e->getMessage());
} catch ( Exception $e ) {
die('Error: ' . $e->getMessage());
}
?>
</body>
</html>

Please update the code, according to the MongoClient PHP manual, now using $m->close() is too expensive and you need not to close the connection in normal circumstances.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.