我在 mongodb 中有两个集合,一个用于帖子,一个用于评论。为每个帖子获取最新评论的最佳方法是什么?我正在寻找类似的解决方案,但对于 mongodb:http ://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/
问问题
160 次
2 回答
0
以防万一其他人有类似的问题,我使用 Map-Reduce 解决了我的问题:
首先,我创建一个这样的地图函数:
$map = "function() { emit(this.post_id, this); }";
和减少功能:
$reduce = "function(k, vals) {".
"var newest = null;".
"for ( var i in vals ) {".
"if ( newest === null ) {".
"newest = vals[i];".
"}".
"else {".
"if ( vals[i]['_id'] > newest['_id'])".
"newest = vals[i]".
"}".
"}".
"return newest;".
"}";
一个包含必要数据的新集合已经准备就绪......
$commentsAggregated = $db->command(array(
"mapreduce" => "comments",
"map" => $map,
"reduce" => $reduce,
"query" => $query,
"out" => array("merge" => "commentsCollectionNew")
));
$getComments = $db->selectCollection($commentsAggregated['result'])->find();
于 2013-08-10T22:19:37.983 回答