2013-03-06 38 views
0

返回不同的数据我有很多帖子的“邮报”的收集,我想从post.published_date的MongoDB:如何使用过滤

返回例如检索不同YearMonth值:

['201303', '201301', '201212' ... ... ] 

我m使用Symfony2 + DoctrineMongoDB。 我想我必须使用QueryBuilder和map和reduce函数,但我无法使用它们!

任何帮助将不胜感激

感谢

+2

请你能张贴和例如文档的结构体? – br3w5 2013-03-06 16:05:49

回答

0

我建议筛选在客户端上的日期,但如果你真的需要在服务器上过滤您可以在聚合框架$放松/ $ addToSet技巧。事情是这样的:

db.post.aggregate([ 
     {$match: ...}, // your match here 
     {$project: { 
       published_date: 1 
     }}, 
     {$unwind: "$published_date"}, 
     {$group: { 
      _id: "$_id", 
      unique_published_date: {$addToSet: "$published_date"} 
     }} 
]) 
0

如果您正在使用的Symfony2和蒙戈DB,您可以创建如下的集合库,并调用库函数findDistinctYearMonth

class PostRepository extends DocumentRepository {  
    public function findDistinctYearMonth() 
      { 
       $yearMonths = $this->createQueryBuilder() 
        ->map('function() { 
        var yearMonth = 
        emit("" + this.published_date.getFullYear()+("0"+(this.published_date.getMonth()+1)).slice(-2),1); 
        }') 
        ->reduce('function(k,v) { 
         return 1; 
        }') 
        ->getQuery() 
        ->execute(); 

    $arr = array(); 
    foreach($yearMonths as $yearMonth) { 
     $arr[] = $yearMonth["_id"]; 
    } 
    return $arr; 
} 
}