Databases Reference
In-Depth Information
Using the array of ancestors approach, when someone wants to create a new comment,
we need to add a new document to the collection. To create this document, we create
a leaf document by linking it to the parent's "_id" value and its array of ancestors.
function createLeaf($parent, $replyInfo) {
$child = array(
"_id" => new MongoId(),
"content" => $replyInfo['content'],
"date" => new MongoDate(),
"votes" => 0,
"author" => array(
"name" => $replyInfo['name'],
"name" => $replyInfo['name'],
),
"ancestors" => $parent['ancestors'],
"parent" => $parent['_id']
);
// add the parent's _id to the ancestors array
$child['ancestors'][] = $parent['_id'];
return $child;
}
Then we can add the new comment to the posts collection:
$comment = createLeaf($parent, $replyInfo);
$posts = $connection->news->posts;
$posts->insert($comment);
We can get a list of the latest submissions (sans comments) with the following:
$cursor = $posts->find(array("ancestors" => array('$size' => 0)));
$cursor = $cursor->sort(array("date" => -1));
If someone wants to see the comments for a given post, we can find them all with the
following:
$cursor = $posts->find(array("ancestors" => $postId));
In fact, we can use this query to access any subtree of comments. If the root of the
subtree is passed in as $postId , every child will contain $postId in its ancestor's array
and be returned.
To make these queries fast, we should index the "date" and "ancestors" keys:
$pageOfComments = $posts->ensureIndex(array("date" => -1, "ancestors" => 1));
Now we can quickly query for the main page, a tree of comments, or a subtree of
comments.
 
Search WWH ::




Custom Search