dongyuan1870 2016-11-22 15:58
浏览 486
已采纳

如何在mongodb querybuilder中“分组”字段“count”?

I want to classify cities with the products they have.

I have two documents: Product and city. The product has its ID and a reference to a city document:

Product(id)             City 

 P1 ------------     Atlanta

 P2 ------------     New York

 P3 ------------     Michigan

 P4 ------------     Atlanta

       ....

I want as result of the query

[Atlant => 23, New York => 35, Michigan => 23, etc..]

But I not being able to get the result.

My actual code is

   public function countBestUsers()
    {
        return $this->createQueryBuilder()
            ->select('id', 'city')
            ->distinct('city')
            ->getQuery()
            ->execute()
            ;
    }
  • 写回答

1条回答 默认 最新

  • dongwen7730 2016-11-22 16:15
    关注

    You can try with group and reduce, this example works for me:

    $count = $dm->createQueryBuilder()->hydrate(false)
            ->group(array('city.$id' => 1), array('value' => 0))
            ->reduce('function (curr,result) {
                result.value++;
            }')
            ->getQuery()
            ->execute()->toArray();
    

    If you need more examples : http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/query-builder-api.html#group-queries

    If you will sort it by the quantities, I recommend use aggregate Framework:

    $pipeline = array('$group' => array(
            '_id' => '$city',
            'value' => array('$sum' => 1)
        )));
    
    array_push($pipeline, array( '$sort' => array('value' => -1) ) );
    
    $count = $dm->getDocumentCollection('YourBundle:Product')
                ->aggregate($pipeline)->toArray();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题