MongoDB:如何通过过滤返回不同的数据



我有一个有很多帖子的"Post"集合,我想从post.published_date中检索不同的YearMonth

返回示例:

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

我使用Symfony2 + DoctrineMongoDB。我想我必须使用QueryBuilder与地图和减少功能,但我不能使用它们!

任何帮助都将不胜感激

谢谢

我建议在客户端过滤日期,但如果你真的需要在服务器端过滤,你可以使用聚合框架的$unwind/$addToSet技巧。像这样:

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

如果您正在使用symfony2和mongo 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;
}
}

最新更新