【问题标题】:MongoDB: how to return distinct data with filteringMongoDB:如何通过过滤返回不同的数据
【发布时间】:2013-02-21 12:14:23
【问题描述】:

我有一个包含很多帖子的“帖子”集合,我想从 post.published_date 检索不同的 YearMonth

返回示例:

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

我正在使用 Symfony2 + DoctrineMongoDB。 我想我必须将 QueryBuilder 与 map 和 reduce 函数一起使用,但我无法使用它们!

任何帮助将不胜感激

谢谢

【问题讨论】:

  • 请您发布您的文档结构示例吗?

标签: mongodb symfony map reduce


【解决方案1】:

我建议在客户端过滤日期,但如果您真的需要在服务器上过滤,您可以使用聚合框架 $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"}
        }}
])

【讨论】:

    【解决方案2】:

    如果您使用的是 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;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      • 2020-11-28
      • 2021-11-18
      • 2022-11-27
      相关资源
      最近更新 更多