【问题标题】:How can I perform a raw query in doctrine mongodb如何在学说 mongodb 中执行原始查询
【发布时间】:2015-02-26 06:56:32
【问题描述】:

有没有办法在 Doctrine 中使用 MongoDB 执行原始查询(就像使用 MySQL 一样)? 我正在尝试这样做:

db.report.aggregate([{"$group" : {_id:"$content", count:{$sum:1}}}])

它似乎也不是 Doctrine 中的原生聚合函数,是吗?

【问题讨论】:

    标签: mongodb doctrine


    【解决方案1】:

    以下对我有用

        $dbName = $this->container->getParameter('mongo_db_name');
    
        $connection = $this->container->get('doctrine_mongodb')->getConnection();
        $mongo = $connection->getMongo();
        $db = $mongo->selectDB($dbName);
    
        $results = $db ->command([
            'aggregate' => 'report',
            'pipeline' => [
                ['$group' => ['_id' => '$content', 'count' => ['$sum' => 1]]]
            ]
        ]);
    
        return $results;
    

    不确定原生 Doctrine 函数,但在聚合的情况下,我更喜欢 RAW JSON 输出,因为它主要用于渲染一些图表。

    【讨论】:

      【解决方案2】:

      在 Doctrine ODM 2.0 中,底层连接由mongodb/mongodb package 处理,而不是由doctrine/mongodb 处理。因此,您可以通过学说 ManagerRegistry::getConnection(), then use the command function using the mongodb library:

      获得连接
      use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
      class Test {
          function execute(ManagerRegistry $mr) {
              $database= $mr->getConnection()->db_name;
      
              $cursor = $database->command([
                  'geoNear' => 'restos',
                  'near' => [
                      'type' => 'Point',
                      'coordinates' => [-74.0, 40.0],
                  ],
                  'spherical' => 'true',
                  'num' => 3,
              ]);
      
              $results = $cursor->toArray()[0];
      
              var_dump($results);
          }
      }
      

      【讨论】:

        【解决方案3】:

        就我而言,我使用聚合

                $db = $mongo->selectDB('ostrov_sync');
                $dbTable = $mongo->selectCollection($db, 'sync_task');
                $results = $dbTable->aggregate([
                    [
                        '$match' => [
                            'payloadHash' => [
                                '$eq' => '0000cfdc-c8cf-11e9-9485-000c29d1ed7a',
                            ],
                        ],
                    ]
                 ]);
        
            dump(results);
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-08
          • 2020-06-30
          • 2014-06-10
          • 1970-01-01
          • 1970-01-01
          • 2018-04-30
          相关资源
          最近更新 更多