Skip to content

Instantly share code, notes, and snippets.

@coderoshi
Forked from lhitchon/gist:1424751
Created February 20, 2012 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coderoshi/1871068 to your computer and use it in GitHub Desktop.
Save coderoshi/1871068 to your computer and use it in GitHub Desktop.
MongoHQ PHP Connection
<!-- 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 = getenv("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>
@shaktisingh
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment