Skip to content

Instantly share code, notes, and snippets.

@heukirne
Last active December 27, 2015 18:29
Show Gist options
  • Save heukirne/7370325 to your computer and use it in GitHub Desktop.
Save heukirne/7370325 to your computer and use it in GitHub Desktop.
MongoDB PHP Blog Example
<?php include('_header.php'); ?>
<?php /* ### Connection ### */
$m = new Mongo("mongodb://guest:guest@host:10047/blogdb");
$db = $m->selectDB("blogdb");
$posts = $db->selectCollection('posts');
?>
<?php /* ### Query ### */
$query = array("title" => "Spoilers Monster High");
$cursor = $posts->find();
$cursor->limit(5);
?>
<div class="row marketing">
<div class="col-lg-6">
<?php
foreach( $cursor as $doc ) {
echo "<h4>{$doc['title']}</h4>";
echo "<p>{$doc['textContent']}</p>";
}
?>
</div>
</div>
<?php /* ### Save ### */
$new_doc = array(
"_id" => new MongoId('52790f749a0ab0ecbf441497'),
"title" => "Spoilers Monster High, save",
'textContent' => "Temos spoilers da Monster High, update.",
);
$posts->save($new_doc);
?>
<?php /* ### Update ### */
$criteria = array("title" => "Spoilers Monster High");
$update = array('$set' => array('textContent' => "Temos spoilers da Monster High, update."));
$options = array();
//$posts->update($criteria, $update, $options);
?>
<?php /* ### Aggregation ### */
/* Listar as tags mais utilizadas na coleção */
$options = array(
array('$unwind' => '$labels'),
array(
'$group' => array(
"_id" => '$labels',
"num" => array('$sum' => 1),
),
),
array('$sort' => array('num'=>-1)),
);
$cursor = $posts->aggregate($options);
?>
<div class="row marketing">
<div class="col-lg-6">
<?php
foreach($cursor['result'] as $doc) {
echo "<h4>{$doc['_id']}</h4>";
echo "<p>{$doc['num']}</p>";
}
?>
</div>
</div>
<?php /* ### Map/Reduce ### */
$map = new MongoCode("function() {
if (this.labels)
this.labels.forEach(function(tag){
emit(tag,1)
});}");
$reduce = new MongoCode("function(k, vals) { return Array.sum(vals) }");
$cursor = $db->command(array(
"mapreduce" => "posts",
"map" => $map,
"reduce" => $reduce,
"out" => array("inline" => 1)));
?>
<div class="row marketing">
<div class="col-lg-6">
<?php
foreach($cursor['results'] as $doc) {
echo "<h4>{$doc['_id']}</h4>";
echo "<p>{$doc['value']}</p>";
}
?>
</div>
</div>
<?php include('_footer.php'); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment